我正在嘗試使用正則運算式從空格分隔的專案中捕獲值。是的,我知道我可以使用[string]::Split()or -split。目標是使用正則運算式以使其適合另一個更大的正則運算式的正則運算式。
字串中有可變數量的專案。在此示例中,有四 (4) 個。生成的 $Matches 變數具有所有 Value 成員的完整字串。我也嘗試了 regex '^((.*)\s*) ',但這導致除了第一個 .\value.txt 之外的所有 ''
如何撰寫正則運算式來捕獲可變數量的專案。
PS C:\src\t> $s = 'now is the time'
PS C:\src\t> $m = [regex]::Matches($s, '^((.*)\s*)')
PS C:\src\t> $m
Groups : {0, 1, 2}
Success : True
Name : 0
Captures : {0}
Index : 0
Length : 15
Value : now is the time
ValueSpan :
PS C:\src\t> $m.Groups.Value
now is the time
now is the time
now is the time
PS C:\src\t> $PSVersionTable.PSVersion.ToString()
7.2.2
uj5u.com熱心網友回復:
您可以使用[regex]::Match()查找第一個匹配的子字串,然后呼叫NextMatch()以推進輸入字串,直到無法進行進一步的匹配。
我冒昧地將運算式簡化為\S (連續的非空白字符):
$string = 'now is the time'
$regex = [regex]'\S '
$match = $regex.Match($string)
while($match.Success){
Write-Host "Match at index [$($match.Index)]: '$($match.Value)'"
# advance to the next match, if any
$match = $match.NextMatch()
}
這將列印:
Match at index [0]: 'now'
Match at index [4]: 'is'
Match at index [7]: 'the'
Match at index [11]: 'time'
uj5u.com熱心網友回復:
我想以下內容對你有用
[^\s]
[^\s]意思是“不是空格”
表示 1 個或多個字符
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451877.html
上一篇:嵌套html標簽的問題
