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

标签 c# regex

我有一个字符串:

<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 内容:翻译罩(内/外键)

    关于c# - 解析 HTML 节点的正则表达式匹配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462731/

    相关文章:

    c# - 锁定数据对象的最佳实践

    c# - 使用本地服务的成员资格表不正确

    c# - (未处理AccessViolationException)如何在C#中实现HandleProcessCorruptedStateExceptions?

    c# - 报告异步任务的进度

    ios - swift/正则表达式 : How can I format a string using stringByReplacingMatches(withTemplate)?

    regex - 用于用户输入验证的 Azure Blob 存储正则表达式模式

    python - 如何检查 DataFrame 字符串列的第一个单词是否存在于 Python 列表中?

    c# - 如何处理组小计,例如WPF DataGrid 中的目标行?

    python - python中具有多个匹配项和否定条件的多行正则表达式

    用于验证前 n 个字符的正则表达式