【发布时间】:2011-11-23 18:52:18
【问题描述】:
如何在 Regex 中转义 html 代码?
我需要找到字符串
&
在类似的字符串中
this is my string & this is another string
我不能为此目的使用 HtmlEncode/Decode,因为我需要使用标签。我想要我只找到公共字符串。
我使用它,例如与“另一个”或“我的”一起使用,但不适用于"&"。
Regex regularextest = new Regex("\b&\b", options);
string RSTest = "char $& morechar";
string lalala = regularextest.Replace("foo & bar", RSTest);
这很令人沮丧,因为 google 将字符串替换为 & 或“AND”字。
提前致谢
【问题讨论】:
-
为什么你需要在字符串上使用正则表达式而不是普通的
.Replace()? -
另外,在 MSDN 中说 & 和 ;不是 C# 中正则表达式的特殊字符
-
见stackoverflow.com/questions/1732348/… 我知道这不是完全重复的,但它回答了你的问题。解析转义的 html 面临同样的限制。
-
我不明白你为什么说“我不能使用 HtmlEncode/Decode ... 因为我需要使用标签” - 你能详细说明一下吗?
-
因为代码的逻辑,正则表达式太复杂了,我把它简化做例子,找到解决办法
标签: c# html regex string html-escape-characters