在PowerShell中过滤以(一个或两个)斜杠开头的字符串

时间:2017-03-20 18:41:24

标签: regex powershell filter powershell-v2.0

我试图找出以斜杠(/)和两个斜杠(//)开头的字符串。例如,以下是具有少量字符串的数组: 以下是我正在尝试的代码:

$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
$arraysplit = $array.split(',');
Foreach ($string in $arraysplit)
{
    if ($string.StartsWith("/"))
    {
        Write-Host "$string has one slash."
    }
    elseif($string.StartsWith("//"))
    {
        Write-Host "$string has two slashes."
    }
    else
    {
        #I want to exit only when below conditions meet
        #1. if string doesnot have any slash or
        #2. if string has more than two slashes
        Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
        Exit -1
    }
}

我不想写更多if条件来过滤事物,但这不能按预期工作。我想我应该改变逻辑来达到要求。有人可以建议我(我正在寻找动态方法)

3 个答案:

答案 0 :(得分:4)

我会编写一个if-test,匹配任何不使用正则表达式的一个或两个斜杠开头的行。尝试:

$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
Foreach ($string in $array)
{
    if ($string -notmatch '^\/{1,2}[^\/]')
    {
        Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
        Exit -1
    }
}

答案 1 :(得分:0)

只是反转你的测试,因为如果一个单词以//开头,则以/

开头
{
    "countries" : 
        [
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          },
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          }
        ]
}

答案 2 :(得分:0)

if ($string -match '^/*') { write-host $matches[0].length slashes }

是@wOxxOm发布的答案。感谢。