【发布时间】: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