计算字符串中字符串的数量?
问题描述:
如何使用Powershell来计算字符串内的字符串数量?计算字符串中字符串的数量?
例如:
$a = "blah test <= goes here/blah test <= goes here/blah blah"
我想数<= goes here /
多少次出现在上面。
答
另一种方式在同一行(类似于@mjolinor方式):
([regex]::Matches($a, "<= goes here /")).count
答
您可以使用[.NET String.Split][1]
方法重载,它接受一个字符串对象数组,然后计算您获得的分割数。
($a.Split([string[]]@('<= goes here /'),[StringSplitOptions]"None")).Count - 1
请注意,您必须强制转换字符串你寻访到字符串数组,以确保您得到正确的Split
过载,然后从结果中减去1,因为分裂将返回所有围绕搜索字符串字符串。同样重要的是,如果搜索字符串在开始或结束时返回,则“无”选项将导致Split返回数组中的空字符串(您可以计数)。
答
使用正则表达式:
$a = "blah test <= goes here/blah test <= goes here/blah blah"
[regex]$regex = '<= goes here /'
$regex.matches($a).count
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!";
- 马库斯
答
只是对BeastianSTI”出色答卷扩大:
寻找一条线的文件用分隔符的最大数量(行未知在运行时):
$myNewCount = 0
foreach ($line in [System.IO.File]::ReadLines("Filename")){
$fields = $line.Split("*").GetUpperBound(0);
If ($fields -gt $myNewCount)
{$myNewCount = $fields}
}
如果您尝试匹配的字符串只有一个字符很长时间。 – 2017-06-29 06:05:44
你如何处理特殊字符?如果你的搜索字符串包含^ \ |(等他们将不得不逃脱。 – 2017-11-21 18:46:42