2013-03-15 58 views

回答

14

另一种方式在同一行(类似于@mjolinor方式):

([regex]::Matches($a, "<= goes here /")).count 
+0

如果您尝试匹配的字符串只有一个字符很长时间。 – 2017-06-29 06:05:44

+0

你如何处理特殊字符?如果你的搜索字符串包含^ \ |(等他们将不得不逃脱。 – 2017-11-21 18:46:42

2

您可以使用[.NET String.Split][1]方法重载,它接受一个字符串对象数组,然后计算您获得的分割数。

($a.Split([string[]]@('<= goes here /'),[StringSplitOptions]"None")).Count - 1 

请注意,您必须强制转换字符串你寻访到字符串数组,以确保您得到正确的Split过载,然后从结果中减去1,因为分裂将返回所有围绕搜索字符串字符串。同样重要的是,如果搜索字符串在开始或结束时返回,则“无”选项将导致Split返回数组中的空字符串(您可以计数)。

3

使用正则表达式:

$a = "blah test <= goes here/blah test <= goes here/blah blah" 
[regex]$regex = '<= goes here /' 
$regex.matches($a).count 
2 
2

我有一堆在它管的字符串。我想知道有多少人,所以我用它来获得它。只是另一种方式:)

$ExampleVar = "one|two|three|four|fivefive|six|seven"; 
$Occurrences = $ExampleVar.Split("|").GetUpperBound(0); 
Write-Output "I've found $Occurrences pipe(s) in your string, sir!"; 
  • 马库斯
0

只是对BeastianSTI”出色答卷扩大:

寻找一条线的文件用分隔符的最大数量(行未知在运行时):

$myNewCount = 0 
foreach ($line in [System.IO.File]::ReadLines("Filename")){ 
    $fields = $line.Split("*").GetUpperBound(0); 
    If ($fields -gt $myNewCount) 
    {$myNewCount = $fields} 
}