【问题标题】:Going backwards with RegEx使用 RegEx 倒退
【发布时间】:2012-12-09 01:15:54
【问题描述】:

我需要解析 iOS 的 *.strings 文件以使用 cmets 获取键/值对。 例如:

/* comment */
"key" = "value";

一旦我找到了该行并检查了它的有效性(我已经设法做到了),我需要捕获它以及它之前的评论。

困难在于:

  • 不是每一行之前都有注释,所以我无法捕获以 /* 开头并以分号结尾的整个块;
  • 下面可能有注释,但该行的格式可能无效,因此应连同其注释一起跳过。

所以我必须检测键/值行,如果存在则上去评论。

RegEx 可以倒退吗?

附:我正在使用 .NET Framework 进行解析:

string[] lines = File.ReadAllLines(fileName);
foreach (string line in lines)
{
    string[] kvp = Regex.Split(line, "\"\\s+?=\\s+?\"");
    if (kvp.Length == 2 && kvp[0].StartsWith("\"") && kvp[1].EndsWith("\";"))
    {
        DataRow row = table.NewRow();
        row["name"] = kvp[0].TrimStart('"');
        row["text"] = kvp[1].Substring(0, kvp[1].Length - 2);
        row["fileId"] = fileId;
        table.Rows.Add(row);
    }
}

【问题讨论】:

  • 评论可以超过一行吗?
  • 理论上 - 是的,但我从未发现过这样的。在多行 cmets 的情况下,我可以使用 string text = File.ReadAllText(fileName);但我无法想象在这种情况下如何找到所有匹配项。
  • 如果您进行逐行阅读,为什么不直接匹配 \"(\w+)\"=\"(\w+)\" 并提取捕获组?

标签: .net regex parsing comments key-value


【解决方案1】:

您甚至可以将搜索的起点设置为向后看:RegexOptions.RightToLeft

【讨论】:

    【解决方案2】:

    您可以在一个正则表达式中完成所有这些操作:

    Match match = null;
    match = Regex.Match(subject, 
        @"(?<=           # Look behind to make sure that there is a comment before:
        (?:              # Try to match...
         /\*             # /*
         (?<comment>     # Capture the comment in the group 'comment'
          (?:            # Match...
           (?!\*/)       # (as long as it's not '*/')
           .             # any character.
          )*             # Repeat as needed.
         )               # End of group 'comment'
         \*/             # Match */
        )?               # Make the whlo comment optional
         \s*             # Match whitespace, including newlines
        )                # End of lookbehind assertion
        ^                # Match the start of the line
        ""               # Match a quote
        (?<name>[^""]*)  # Capture any number of non-quote characters into group 'name'
        ""\s*=\s*""      # Match quote - equals - quote, with optional whitespace
        (?<value>[^""]*) # Capture any number of non-quote characters into group 'text'
        "";              # Match the closing quote and semicolon", 
        RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
    row["name"] = match.Groups["name"];
    row["text"] = match.Groups["text"];
    row["comment"] = match.Groups["comment"];
    

    【讨论】:

    • 如果您使用regex101.com 自动为您解释这些正则表达式,您会节省很多时间:)
    • @Lindrian:不起作用:那个正则表达式引擎不支持可变长度的lookbehinds。另外,我发现这些机器生成的解释通常不是很有帮助......
    • @Lindrian:关于 regex101 的非常好的建议!比桌面程序好多了!至于正则表达式本身:键和值可能包含转义字符:\" \= 等
    • @TimPietzcker:你是对的。它使用不支持可变长度后视的 PHP。尽管如此,以我的拙见,它在解释正则表达式方面做得非常好。 (解释它不会有任何问题,但由于它同时运行匹配,你会从 php 得到一个错误)
    • @Paul:看看我的正则表达式,它处理转义值。
    【解决方案3】:

    正则表达式永远不会倒退,即使您要执行.+$ 之类的操作。但是你可以让它看起来好像它们是向后工作的。但是,这对于此任务来说并不是真正必要的。

    您可以使用以下正则表达式:

    /^(?<comment>(?:\/\*(?:(?!\*\/).)*\*\/)?\s*)(?<key>"(?:\\.|[^"])+")\s*=\s*(?<value>"(?:\\.|[^"])+")\s*;/gms
    

    (不确定在 .net 中是否需要分隔符和全局标志)

    所以基本上,第一个反向引用将保存评论。第二个将保存密钥,第三个将保存值。如果您对键/值完全不感兴趣,则可以通过将最后两个反向引用合并为一个来进一步简化正则表达式。

    您现在拥有所需的所有数据。只需相应地更换。如果第一个反向引用包含 null 值,则您知道该行上方没有注释。

    演示+说明:http://regex101.com/r/xN1uQ4

    如果有不清楚的地方,请询问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多