Skip to main content
 首页 » 编程设计

c#之解析 HTML 节点的正则表达式匹配失败

2024年01月18日52www_RR

我有一个字符串:

<graphic id="8374932">Translating Cowl (Inner/Outer Bondments</graphic> 

我的模式:
"<graphic id=\"(.*?)\">(.*?)</graphic>" 

但是第二组失败了,说:“不够)。”我应该如何预防?

请您参考如下方法:

编辑:首先,如果您的目标是解析 HTML 或 XML,我强烈建议您不要这样做。如果您的目标是学习或通过外科手术抓取元素节点,那么正则表达式可能,我说可能是一种使用工具。我在回答这个问题时认为您正在使用 html 模式来学习....

我相信您已经将您的数据与您的模式混淆了,并且正则表达式模式失败了。

我推荐这些东西

  • 不要使用.*?获取文本。对于正则表达式解析器来说太模糊了。在你的模式中更加简洁。
  • 由于您知道文本用引号或 >xxx< 括起来,因此请使用它们作为 anchor 。
  • 确定 anchor 后,提取文本
  • 将捕获的文本放入命名的捕获组。

  • 如何获取文本?告诉正则表达式解析器获取 的所有内容不是 通过使用带有 ^ 的集合操作的 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:8374​​932 内容:翻译罩(内/外键)