1

我有一个需要修改 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 。

谢谢!

4

1 回答 1

1

您可以使用 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)
)
于 2021-04-14T11:27:15.513 回答