以下結果是“foo”的單個匹配。
$multilineString = "foo
bar
baz";
$multilineString -match ".*";
$matches;
那是因為該.字符不包括換行符。
這些也只輸出“foo”。
$multilineString -match "(.|\r)*" | Out-Null; $matches[0];
$multilineString -match "(.|\r\n)*" | Out-Null; $matches[0];
在 PowerShell 中,我們如何使用 match 來包含任何字符,包括換行符,以便輸出將包含所有三行:
foo
bar
baz
uj5u.com熱心網友回復:
我幾乎從不-match用于這種特定用途,就像在我的評論中一樣,我通常使用[regex]. 查看 MS 檔案后:
請務必注意,
$Matches哈希表僅包含任何匹配模式的第一次出現。
因此,如果您想獲得與 相同的結果[regex]::Matches($multilineString, '\w ').Value,則需要首先拆分字串,然后對其進行回圈:
$multilineString = "foo
bar
baz"
$multilineString -split '\r?\n' | ForEach-Object {
if($_ -match '\w ')
{
$Matches
}
}
Name Value
---- -----
0 foo
0 bar
0 baz
一個也可以作業并且不需要拆分或回圈的替代方法是可能的,但regex模式必須更具體。在這種情況下,我們知道我們正在尋找 3 個單詞。
$multilineString = "foo
bar
baz"
$multilineString -match '^(\w )\s (\w )\s (\w )$'
$Matches
Name Value
---- -----
3 baz
2 bar
1 foo
0 foo…
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371273.html
