【问题标题】:RegEx Replace with character substitution in captured group正则表达式替换为捕获组中的字符替换
【发布时间】:2020-08-24 07:34:05
【问题描述】:

我可以使用正则表达式获取我感兴趣的字符串,但是如何将其替换为捕获中替换的字符?

我想从任何 html 属性中删除 > 字符,或将其替换为 >

原始字符串示例

<html> 
<head></head> 
<body> 
<div  sometag="abc>def" onclick="myfn()" class='xyz'>
Dear {@CustomerName},
blah blah blah
</div></body> 
</html>

想要的结果

<html> 
<head></head> 
<body> 
<div  sometag="abc&gt;def" onclick="myfn()" class='xyz'>
Dear {@CustomerName},
blah blah blah
</div></body> 
</html>

我正在使用以下正则表达式模式和替换

模式\s\w+\s*=\s*(['"])[^\1]+?\1

替换-- don't know! what should I use? --

这是我的vb.net 代码(以防万一)

Dim reAttr As New Regex("\s\w+\s*=\s*(['""])[^\1]+?\1", RegexOptions.Singleline)
result = reAttr.Replace(text, Replace("$&", ">", ""))

【问题讨论】:

    标签: .net regex vb.net regexp-replace


    【解决方案1】:

    你可以使用

    Dim reAttr As New Regex("\s\w+\s*=\s*(['""])(?:(?!\1).)*?\1", RegexOptions.Singleline)
    Dim result = reAttr.Replace(text, New MatchEvaluator(Function(m As Match)
             Return m.Value.Replace(">", "-")
         End Function))
    

    请注意,[^\1] 没有达到您的预期,它匹配除 SOH 字符 (\x01) 之外的任何字符。 (?:(?!\1).)*? tempered greedy token 可以满足您的要求,它匹配除第 1 组中捕获的值之外的任何字符,0 次或更多次,尽可能少。

    MatchEvaluator 用作替换参数,您可以使用m.Value 访问整个匹配值。

    【讨论】:

    • 完美运行!太感谢了。我在这上面浪费了一整天。此外,[\1] 正在选择我期待的字符串部分,所以对此感到困惑。也感谢您的纠正。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多