【问题标题】:Regex to fetch substring from a string正则表达式从字符串中获取子字符串
【发布时间】:2017-06-07 21:29:39
【问题描述】:

我正在使用 notepad++ 并尝试用特定标记内的另一个单词查找/替换 XML 文件中出现的特定单词。

例如: XML 文件包含

<alerts>
     <ccEmails>abc@example.com,xyz@example.com</ccEmails>
     <toEmails>mnp@example.com</toEmails>            
</alerts>

我需要将 example 替换为存在 inside&lt;ccEmails&gt;not inside&lt;toEmails&gt;

我在https://regex101.com/r/Q8UB6a/1 尝试了ccEmails.*(example).*ccEmails,它只返回最后一次出现。另外,我无法用另一个字符串替换那里的字符串。

当我在记事本++中尝试这个时,我得到了&lt;ccEmails&gt;中的所有字符串

您能帮我查找/替换特定标签中包含的子字符串吗?如果需要更多详细信息,请告诉我。

【问题讨论】:

    标签: regex string replace notepad++


    【解决方案1】:

    如果您打算使用“查找和替换”对话框,则需要使用基于 \G 的正则表达式,例如

    (?:<ccEmails>|\G(?!^))[^<]*?\K\bexample\b
    

    并替换为myexample。查看online regex demo.

    详情

    • (?:&lt;ccEmails&gt;|\G(?!^)) - &lt;ccEmails&gt; 或最后一次成功匹配的结束
    • [^&lt;]*? - 除&lt; 之外的任何 0+ 字符尽可能少
    • \K - 省略目前匹配的文本 -\bexample\b - 整个词example

    【讨论】:

      【解决方案2】:

      (&lt;ccEmails&gt;[^&lt;&gt;]+@)example\. 替换为\1myexample. 并进行全部替换。全部替换需要执行两次或更多次,因为每次传递只会更改所需字符串中的一个example

      【讨论】:

        猜你喜欢
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 2010-10-14
        相关资源
        最近更新 更多