我有一个文件,我需要在其中修改 URL,但不知道该 URL 包含什么,就像在下面的示例中一样:在文件 file.txt 中,我必须替换 URL,以便它是“https://SomeDomain /Release/SomeText”或“https://SomeDomain/Staging/SomeText”到“https://SomeDomain/Deploy/SomeText”。因此,无论 SomeDomain 和 SomeText 之间写什么,都应该用已知的字符串替换。是否有任何正则表达式可以帮助我实现这一目标?
我曾经使用以下命令来做到这一点”
((Get-Content -path "file.txt" -Raw) -replace '"https://SomeDomain/Release/SomeText");','"https://SomeDomain/Staging/SomeText");') | Set-Content -Path "file.txt"
这工作正常,但我必须在执行命令之前知道 file.txt 中的 URL 是否包含 Release 或 Staging。
谢谢!
您可以使用正则表达式执行此操作,您可以-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)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句