【问题标题】:regex=>lookahead between two matches c#正则表达式=>两个匹配之间的前瞻c#
【发布时间】:2012-10-02 06:16:23
【问题描述】:
const string numericReg = "\\d+"; // Matches a digit character. Equivalent to [0-9].
const string realNumsReg = numericReg + b + "(\\." + b + numericReg + ")?";
        const string b = "\\s*";

这句话是真的:

  private const string rte = "(?<rate>" + realNumsReg + ")" +
                            "(?=(?<rte1>" + b + "qs " + "))";

这句话是真的:

 private const string barl = "(?<barl>" + numericReg + ")" +
                                    "(?=((?<q>" + b + "point to print )))";

rte 是这样:

  MatchCollection s = Regex.Matches
                ("3000 qs / min", rte , RegexOptions.IgnoreCase);

barl 也是这样:

  MatchCollection s = Regex.Matches
                ("6 point to print  ", barl , RegexOptions.IgnoreCase);

为什么会这样?

  MatchCollection s = Regex.Matches
                ("6 point to print  3000 qs/ min", barl+b+rte  , RegexOptions.IgnoreCase);

【问题讨论】:

    标签: regex c#-4.0 lookahead


    【解决方案1】:

    第一个问题: 3,000 中的逗号 (',')。 第一个匹配项匹配“000 rds” 在第三个 Regex.Matches 中没有任何内容可以匹配“3”。

    第二个(不太明显的问题):

    这两个前瞻断言 (?=expression) 是不匹配的断言,因此没有任何内容与第三个 Regex 中的第一个断言内的任何内容相匹配。

    在你的情况下:'barl' + 'b' + 'rte'

    'barl' 匹配 '6 buckets per mount' 中的 '6','b' 匹配 '6' 和 'barrels' 之间的空间('barrels per mount' 由前瞻断言但不匹配)并且 'rte' 不能匹配后跟 'rds' 的数字。

    只需从您的表达式中删除逗号和前瞻,您实际上并不需要它们,因为您感兴趣的组无论如何都已命名,并且可以从 Match 中的 Groups 集合中轻松获得它们匹配的内容。

    改进:

    1. 您可能希望更改 rte 以匹配 'qs / min' 中的 '/ min' 而不仅仅是 qs。
    2. 将 numericReg 更改为 @"\d+(,\d{3})*(.\d+)?" (匹配任意数量的数字,后跟零个或多个逗号,正好是 3 个数字组和一个或零组点,后跟数字)。此正则表达式匹配以下形式的数字:3000 3,000 3,000.0000

    【讨论】:

    • 你的意思是这不是唯一的问题。我之前没有发现的另一个问题是前瞻断言 (?=)。我正在编辑我的回复以包含此错误。
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2020-04-15
    相关资源
    最近更新 更多