【发布时间】:2021-12-02 07:46:09
【问题描述】:
以下结果为“foo”的单个匹配项。
$multilineString = "foo
bar
baz";
$multilineString -match ".*";
$matches;
那是因为the . character does not include line breaks。
这些也只输出“foo”。
$multilineString -match "(.|\r)*" | Out-Null; $matches[0];
$multilineString -match "(.|\r\n)*" | Out-Null; $matches[0];
在 PowerShell 中,我们如何使用 match 来包含任何字符,包括换行符,以便输出包含所有三行:
foo
bar
baz
【问题讨论】:
-
您需要使用
(?ms).*。有关详细信息,请参阅this answer。如果您使用的是[regex]::Matches(...),则同样适用 -
如果您只想匹配 3 个单词而无需修剪前导和尾随空格,您可以使用
[regex]::Matches($multilineString, '\w+').Value。 -
@SantiagoSquarzon 感谢
(?ms).*的提示。此外,对于这个用例,我们使用-match运算符很重要。 -
我不知道你将如何使用
-mach获得与[regex]::Matches($multilineString, '\w+').Value相同的结果(包含3 个单词的数组),除非你对字符串执行-split '\r?\n'然后循环遍历每个元素。
标签: windows powershell