正则表达式匹配失败解析HTML节点

und*_*ver 1 c# regex

我有一个字符串:

<graphic id="8374932">Translating Cowl (Inner/Outer Bondments</graphic>
Run Code Online (Sandbox Code Playgroud)

我的模式:

"<graphic id=\"(.*?)\">(.*?)</graphic>"
Run Code Online (Sandbox Code Playgroud)

但第二组却失败了,他说:"还不够." 我应该如何预防呢?

Ωme*_*Man 10

编辑:首先,如果您的目标是解析HTML或XML,我强烈反对它.如果你的目标是学习或手术抓取一个元素节点,那么正则表达式可能,我说可能是一个使用的工具.我正在回答这个想法,你正在使用html模式来学习....

我相信你的数据与你的模式混淆了,正则表达式模式失败了.

我推荐这些东西

  1. 不要使用.*?得到文字.它对于正则表达式解析器来说太模糊了.在你的模式中更简洁.
  2. 由于您知道文本用引号括起来或者用> xxx <用作锚点.
  3. 确定锚点后,提取文本
  4. 将捕获的文本放入命名的捕获组.

如何获取文字?告诉正则表达式解析器通过使用set操作来获得不是锚字符的everthing ^(这意味着不在一个集合中[ ]),例如([^\"]+)匹配所有不是引用的内容.

将您的模式更改为此,以演示上述建议:

string data = @"<graphic id=""8374932"">Translating Cowl (Inner/Outer Bondments</graphic>";

 // \x22 is the hex escape for the quote, makes it easier to read.
string pattern = @"
(?:graphic\s+id=\x22)  # Match but don't capture (MBDC) the beginning of the element
(?<ID>[^\x22]+)        # Get all that is not a quote
(?:\x22>)              # MBDC the quote
(?<Content>[^<+]+)     # Place into the Content match capture group all text that is not + or <  
(?:\</graphic)         # MBDC The graphic";

// Ignore Pattern whitespace only allows us to comment, does not influence regex processing.
var mt = Regex.Match(data, pattern, RegexOptions.IgnorePatternWhitespace);

Console.WriteLine ("ID: {0} Content: {1}", mt.Groups["ID"], mt.Groups["Content"]);
Run Code Online (Sandbox Code Playgroud)

//输出:
// ID:8374​​932内容:翻译罩(内/外键合