[英].NET regex expression to find enclosed text
我需要用标记语法替换所有出现在简单标记中的字符串。 例如:我需要转换看起来像这样的字符串:
"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>"
换句话说, match.Value包括星号。
我确定了我可以使用的另一个正则表达式:
(?<=\*\*).+?(?=\*\*)
这将产生正确的第一场比赛,但对于随后的比赛是错误的; 如上述代码段中所使用的,对于第二个示例字符串,我得到以下匹配序列( match.Value ):
this
text
needs
to be displayed
bold
它似乎返回的是每次出现在星号对之间的字符串,而不是根据需要将它们“配对”。
如果我使用诸如rubular之类的在线正则表达式工具,则我的初始解决方案似乎做对了(星号从匹配项中删除),但这不是.NET实现返回的结果。
是否可以使用正则表达式字符串来获得所需的结果,还是必须对匹配项进行一些后处理?
有时,为了获得更多控制权,我更喜欢使用使用MatchEvaluator
委托的Regex.Replace重载版本:
Regex.Replace(input,
@"\*\*(?<a>.*?)\*\*",
m => string.Format("<bold>{0}</bold>", m.Groups["a"].Value))
尽管对于这样一个简单的任务:
Regex.Replace(input,
@"\*\*(?<a>.*?)\*\*",
@"<bold>${a}</bold>")
就足够了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.