所以可以說我有一個多行字串,如下所示。
#abc
abc def
abc
我只想用 xyz 替換從新行開始的 abc 的第一個實體,同時忽略它前面的任何空格(如上例所示)
所以我替換的字串應該是
#abc
xyz def
abc
不太擅長正則運算式,所以希望得到建議。謝謝!
uj5u.com熱心網友回復:
為此,您需要一個固定到行首的正則運算式,允許多個前導空格并使用單詞邊界來確保您不會替換較大字串的一部分。
$multilineText = @"
#abc
abc def
abc
"@
$toReplace = 'abc'
$replaceWith = 'xyz'
# create the regex string.
# Because the example `abc` in real life could contain characters that have special meaning in regex,
# you need to escape these characters in the `$toReplace` string.
$regexReplace = '(?m)^(\s*){0}\b' -f [regex]::Escape($toReplace)
# do the replacement and capture the result to write to a new file perhaps?
$result = ([regex]$regexReplace).Replace($multilineText, "`$1$replaceWith", 1)
# show on screen
$result
以上作業區分大小寫,但如果您不想要那樣,只需在定義中更改(?m)為。(?mi)$regexReplace
輸出:
#abc
xyz def
abc
正則運算式詳細資訊:
(?m) Match the remainder of the regex with the options: ^ and $ match at line breaks (m)
^ Assert position at the beginning of a line (at beginning of the string or after a line break character)
( Match the regular expression below and capture its match into backreference number 1
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
){0}
\b Assert position at a word boundary
正則運算式中的特殊字符
| 字符 | 描述 | 意義 |
|---|---|---|
| \ | 反斜杠 | 用于轉義特殊字符 |
| ^ | 插入符號 | 字串的開頭 |
| $ | 美元符號 | 字串的結尾 |
| . | 句點或點 | 匹配任何單個字符 |
| | | 豎線或豎管符號 | 匹配上一個或下一個字符/組 |
| ? | 問號 | 匹配零個或前一個 |
| * | 星號或星號 | 匹配零個、一個或多個先前的 |
| 加號 | 匹配前一個或多個 | |
| ( ) | 左括號和右括號 | 組字符 |
| [ ] | 開閉方括號 | 匹配一系列字符 |
| { } | 打開和關閉花括號 | 匹配指定次數的前一個 |
uj5u.com熱心網友回復:
1 只是用字串中的 'xyz' 替換了 'abc' 的第一個實體。
Write-Host "Replace Example One" -ForegroundColor Yellow -BackgroundColor DarkGreen
$test = " abc def abc "
[regex]$pattern = "abc"
$pattern.replace($test, "xyz", 1)
Write-Host "Replace Example Two" -ForegroundColor Green -BackgroundColor Blue
$test = Get-Content "c:\test\text.txt"
[regex]$pattern = "abc"
$x = $pattern.replace($test, "xyz", 1)
Write-Host $x
Write-Host "Replace Example Three" -ForegroundColor White -BackgroundColor Red
$multilineText = @"
#abc
abc def
abc
"@
[regex]$pattern = "abc"
$y = $pattern.replace($multilineText, "xyz", 1)
Write-Host $y

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380567.html
標籤:电源外壳
上一篇:創建用于發送電子郵件的附件陣列
