2

嘿,我目前正在尝试替换字符串中的 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# 顺便说一句。)

4

3 回答 3

5

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

用于(…)在正则表达式中捕获:

text = Regex.Replace(text, "<strong>(.*?)</strong>", "<b>$1</b>");
于 2013-01-28T11:54:44.983 回答
2

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

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>");
于 2013-01-28T11:58:06.293 回答
0

您还可以考虑使用:

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

Note that RegexOptions.Singleline is necessary to allow . to match line feed (LF, \x0A) characters, that the . pattern cannot match by default.

于 2021-10-21T12:56:16.560 回答