【问题标题】:How can we replace multiple match with only one word/phrase replace using powershell我们如何使用powershell仅用一个单词/短语替换替换多个匹配项
【发布时间】:2014-08-19 03:13:01
【问题描述】:

我们如何使用 powershell 用一个单词/短语替换多个匹配项

以下是正则表达式中的匹配项

授予对 Server1 的访问权限
授予对 Server2 的访问权限
授予对 Server3 的访问权限
授予对 Server4 的访问权限

只需将上面的所有结果替换为下面的一个短语,

每日一语!

【问题讨论】:

  • 到目前为止您尝试过什么?这些示例中是否包含其他内嵌文本?
  • 使用.*,您已设置为regex101.com/r/mZ1fA9/1
  • @Matt,是的,还有其他文字,我只显示来自正则表达式的匹配。
  • 你的代码是什么样的?
  • 这是我当前的代码。 /Grant access to \w+/g 但只需要用一个短语替换它。不是每场比赛。我正在使用 powershell

标签: regex powershell powershell-ise


【解决方案1】:

我不完全确定 OP 的用途,但您希望将所有行与以下内容匹配

Grant access to Server1
Grant access to Server2
Grant access to Server3
Grant access to Server4

您可以将其用作您的模式(Grant access to Server\d+(\n)?){4}。这将匹配原始文本“授予对服务器的访问权限”,后跟至少一位数字。如果最后一项位于字符串的末尾(最后一项不会有换行符),我们会为换行符添加可选的(\n)?。最后是 {4} 的限定词,因为该示例仅出现 4 次。您可以轻松地将 {4} 替换为 * 作为对所有事件按顺序的贪婪捕获。

所以(Grant access to Server\d+(\n)?)* 也会匹配:

Grant access to Server1
Grant access to Server3
Grant access to Server44325
Grant access to Server4
Grant access to Server44
Grant access to Server3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2020-12-09
    • 2011-10-07
    相关资源
    最近更新 更多