2013-03-15 87 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} 
}