您可以使用 regex 执行此操作-replace
,在其中捕获您希望保留的部分并使用反向引用重新创建新字符串
$fileName = 'Path\To\The\File.txt'
$newText = 'BLAHBLAH'
# read the file as single multilined string
(Get-Content -Path $fileName -Raw) -replace '(https?://\w+/)[^/]+(/.*)', "`$1$newText`$2" | Set-Content -Path $fileName
正则表达式详细信息:
( Match the regular expression below and capture its match into backreference number 1
http Match the characters “http” literally
s Match the character “s” literally
? Between zero and one times, as many times as possible, giving back as needed (greedy)
:// Match the characters “://” literally
\w Match a single character that is a “word character” (letters, digits, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
/ Match the character “/” literally
)
[^/] Match any character that is NOT a “/”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
( Match the regular expression below and capture its match into backreference number 2
/ Match the character “/” literally
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)