繁体   English   中英

我的 Regex.Replace 不起作用

[英]My Regex.Replace doesn't work

嘿,我目前正在尝试替换字符串中的 html。 <strong>text</strong>需要是<b>text</b>等(我意识到b标签被认为是过时的)

我知道我不应该使用正则表达式来解决这个问题,但这是目前我唯一的选择

我的代码:

//replace strong
text = Regex.Replace(text, "<strong>.*?</strong>", "<b>$1</b>");

//replace em
text = Regex.Replace(text, "<em>.*?</em>", "<i>$1</i>");

这里的问题是正则表达式替换了标签并将文本设置为$1 如何避免这种情况? (顺便说一句,我在 C# 中。)

$1将使用匹配中第一个捕获的值。 但是你没有在比赛中指定任何捕获组,所以没有任何东西可以用$1来代替。

使用(…)捕获正则表达式:

text = Regex.Replace(text, "<strong>(.*?)</strong>", "<b>$1</b>");

请注意,以下答案只是一种解决方法; 写一个正确的正则表达式更好。

var text = "<strong>asfdweqwe121</strong><em>test</em>";

text = text.Replace("<strong>", "<b>");
text = text.Replace("</strong>", "</b>");
text = text.Replace("<em>", "<i>");
text = text.Replace("</em>", "</i>");

您还可以考虑使用:

text = Regex.Replace(text, "<strong>(.*?)</strong>", "<b>$1</b>", RegexOptions.Singleline);

请注意, RegexOptions.Singleline是允许. 匹配换行符 (LF, \\x0A ) 字符,即. 模式默认无法匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM