【问题标题】:Filter the strings which startswith (one or two) slashes in PowerShell在 PowerShell 中过滤以(一个或两个)斜杠开头的字符串
【发布时间】:2017-08-12 04:46:30
【问题描述】:

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

$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 条件来过滤这些东西,但这并没有按预期工作。我想我应该改变逻辑来实现要求。有人可以建议我(我正在寻找动态方法)

【问题讨论】:

  • if ($string -match '^/*') { write-host $matches[0].length slashes }
  • 如果保证只有前导斜线,那么(($array[$i] -split "/").length) - 1是前导斜线的数量。
  • 我应该注意到,这看起来更像是一个家庭作业问题...
  • @wOxxOm 这听起来像是一个答案。
  • 对于它的价值,我不知道为什么除了糟糕的标题之外你还投反对票。我很高兴看到你尝试一些东西。

标签: regex powershell filter powershell-2.0


【解决方案1】:

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

$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
    }
}

【讨论】:

  • 我知道它在问题中,但我会删除 $arraysplit 逻辑。 $array 已经是一个数组了。
  • 不用转义/
  • 也许不是,但是 regex101 喜欢它(PHP 引擎)并且它不会受到伤害。 :-)
  • @FrodeF。它有助于。谢谢。
  • 好吧,\/ 可读性较差,regex101 也有一个风味选项:您可以将其切换为 golang。
【解决方案2】:

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

$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
$arraysplit = $array.split(',');
Foreach ($string in $arraysplit)
{
    if ($string.StartsWith("//"))
    {
        Write-Host "$string has two slash."
    }
    elseif($string.StartsWith("/"))
    {
        Write-Host "$string has one 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
    }
}

【讨论】:

    【解决方案3】:
    if ($string -match '^/*') { write-host $matches[0].length slashes }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多