[英]Regex to match words but not html entities
我正在用正则表达式解析html节点文本,以查找要对其执行操作的单词。
我正在使用(\\w+)
我遇到类似word word
,并且nbsp被识别为一个单词。
我可以将html实体与\\&[a-z0-9A-Z]+\\;
匹配\\&[a-z0-9A-Z]+\\;
但是我不知道如果单词是实体的一部分,如何使单词不匹配。
有没有办法让正则表达式匹配一个单词,但是如果它是如下所示的html实体,则不可以?
<
<
ý
ý
等
而是第一次使用:
System.Web.HttpUtility.HtmlDecode(...)
要么
System.Net.WebUtility.HtmlDecode(...)
在您的HTML上。
解码会将所有转义的字符转换为正常表示。 之后,使用正则表达式解析解码的HTML。
由于您使用的是C#,因此可以进一步检查完整的
实体形式。
这使用条件在单词边界处进行检查
前分号。 如果在那儿,它会向后使用以确保
这不是实体。
# @"(?i)(\w+)\b(?(?=;)(?<!(?:&|%)(?:[a-z]+|(?:\#(?:[0-9]+|x[0-9a-f]+)))(?=;)))"
(?i)
( \w+ ) # (1)
\b
(?(?= ; ) # Conditional. Is ';' the next character ?
(?<! # Yes, then this word cannot be part of an entity
(?: & | % )
(?:
[a-z]+
| (?:
\#
(?:
[0-9]+
| x [0-9a-f]+
)
)
)
(?= ; )
)
)
码:
string input = @"
< <
ý ý
etc etc
I have situations like word word and the nbsp gets recognized as a word.
";
Regex RxNonEntWords = new Regex(@"(?i)(\w+)\b(?(?=;)(?<!(?:&|%)(?:[a-z]+|(?:\#(?:[0-9]+|x[0-9a-f]+)))(?=;)))");
Match _m = RxNonEntWords.Match( input );
while (_m.Success)
{
Console.WriteLine("Found: {1}", _m.Groups[1].Value);
_m = _m.NextMatch();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.