正则表达式捕获可变数量的项目?

Regex to capture a variable number of items?

我正在尝试使用正则表达式从 SPACE 分隔项中捕获值。是的,我知道我可以使用 [string]::Split()-split。目标是使用正则表达式以使其适合另一个更大的正则表达式的正则表达式。

字符串中的项目数量可变。在此示例中,有四 (4) 个。生成的 $Matches 变量具有所有 Value 成员的完整字符串。我也尝试了正则表达式 '^((.*)\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

我想下面的内容对你有用

[^\s]+

[^\s] 表示“不是 space”

+表示1个或多个字符

您可以使用 [regex]::Match() 找到 第一个 匹配的子字符串,然后调用 NextMatch() 继续输入字符串,直到无法进行进一步的匹配.

我冒昧地将表达式简化为 \S+(连续 non-whitespace 个字符):

$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'