【问题标题】:.NET regex expression to find enclosed text.NET 正则表达式来查找封闭的文本
【发布时间】:2014-11-28 19:03:55
【问题描述】:

我需要用标记语法替换所有出现在简单标记中的字符串。例如:我需要转换如下所示的字符串:

"this text needs to be displayed **bold**"

"**this** text **needs** to be displayed **bold**"

对这些:

"this text needs to be displayed <bold>bold</bold>"

"<bold>this</bold> text <bold>needs</bold> to be displayed <bold>bold</bold>"

如果我使用以下内容:

string inputString = "this text needs to be displayed **bold**";
var reg = new Regex(@"\*\*([^\*]+)\*\*");
var outputString = reg.Replace(inputString, match => "<bold>" + match.Value + "</bold>");

输出字符串如下所示:

"this text needs to be displayed <bold>**bold**</bold>"

换句话说,ma​​tch.Value 包括星号。

我已经确定了另一个我可以使用的正则表达式:

(?<=\*\*).+?(?=\*\*)

这会产生正确的第一次匹配,但对于后续匹配不正确;如上面代码 sn-p 中使用的那样,我得到了第二个示例字符串的以下匹配序列 (ma​​tch.Value):

this
 text 
needs
 to be displayed
bold

它似乎是返回每个出现在星号对之间的字符串,而不是根据需要将它们“配对”。

如果我使用像 rubular 之类的在线正则表达式工具,我最初的解决方案似乎是正确的(星号已从匹配项中删除),但这不是 .NET 实现返回的内容.

是否有一个正则表达式字符串可以用来实现我所追求的结果,还是我必须对匹配项进行一些后处理?

【问题讨论】:

  • 我很抱歉,但这永远不会以强大的方式工作,请参阅stackoverflow.com/questions/16358582/… 以获取有关原因的提示。如果您希望它可靠,请忘记正则表达式并编写有状态解析器。

标签: c# .net regex


【解决方案1】:

在替换调用中引用捕获组。

var outputString = reg.Replace(inputString, "<bold>$1</bold>");

Ideone Demo

【讨论】:

    【解决方案2】:

    有时,为了获得更多控制,我更喜欢使用Regex.Replace 的重载版本,它使用MatchEvaluator 委托:

    Regex.Replace(input,
                  @"\*\*(?<a>.*?)\*\*",
                  m => string.Format("<bold>{0}</bold>", m.Groups["a"].Value))
    

    虽然对于这么简单的任务:

    Regex.Replace(input,
                  @"\*\*(?<a>.*?)\*\*", 
                  @"<bold>${a}</bold>")
    

    足够了

    【讨论】:

    • 一个非常有用但鲜为人知的委托重载
    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2021-06-20
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多