[英]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.