我有一个字符串:
<graphic id="8374932">Translating Cowl (Inner/Outer Bondments</graphic>
我的模式:
"<graphic id=\"(.*?)\">(.*?)</graphic>"
但是第二组失败了,说:“不够)。”我应该如何预防?
最佳答案
编辑:首先,如果您的目标是解析 HTML 或 XML,我强烈建议您不要这样做。如果您的目标是学习或通过外科手术抓取元素节点,那么正则表达式可能,我说可能是一种使用工具。我在回答这个问题时认为您正在使用 html 模式来学习....
我相信您已经将您的数据与您的模式混淆了,并且正则表达式模式失败了。
我推荐这些东西
如何获取文本?告诉正则表达式解析器获取 的所有内容不是 通过使用带有
^
的集合操作的 anchor 字符(这意味着 不是 在集合中时 [ ]
)例如 ([^\"]+)
它说匹配所有不是引用的东西。将您的模式更改为展示上述建议的模式:
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"]);
//输出:
//ID:8374932 内容:翻译罩(内/外键)
关于c# - 解析 HTML 节点的正则表达式匹配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462731/