如何进行平衡组捕获?

时间:2013-09-26 11:30:30

标签: c# regex balancing-groups expresso

假设我有这个文字输入。

 tes{}tR{R{abc}aD{mnoR{xyz}}}

我想提取ff输出:

 R{abc}
 R{xyz}
 D{mnoR{xyz}}
 R{R{abc}aD{mnoR{xyz}}}

目前,我只能使用msdn中的平衡组方法提取{}组内的内容。这是模式:

 ^[^{}]*(((?'Open'{)[^{}]*)+((?'Target-Open'})[^{}]*)+)*(?(Open)(?!))$

有人知道如何在输出中包含R {}和D {}吗?

3 个答案:

答案 0 :(得分:3)

我认为这里需要采用不同的方法。在匹配第一个较大的群组R{R{abc}aD{mnoR{xyz}}}后(请参阅我对可能的拼写错误的评论),由于正则表达式不允许您捕获个人,因此您无法在内部获取子群组{ {1}}群组。

所以,必须有一些方法来捕获而不是消费,显而易见的方法是使用积极的前瞻。从那里,你可以把你使用的表达,虽然有一些变化,以适应新的焦点变化,我想出了:

R{ ... }

[我也改名为' Open'到了' O'并删除了近大括号的命名捕获,使其缩短并避免在匹配中产生噪音]

在regexhero.net(我目前唯一知道的免费.NET正则表达式测试程序)中,我得到了以下捕获组:

(?=([A-Z](?:(?:(?'O'{)[^{}]*)+(?:(?'-O'})[^{}]*?)+)+(?(O)(?!))))

正则表达式的细分:

1: R{R{abc}aD{mnoR{xyz}}}
1: R{abc}
1: D{mnoR{xyz}}
1: R{xyz}

以下内容在C#

中不起作用

我实际上想试试它应该如何在PCRE引擎上运行,因为可以选择使用递归正则表达式,我认为它更容易,因为我对它更熟悉并且产生了更短的正则表达式:)

(?=                         # Opening positive lookahead
    ([A-Z]                  # Opening capture group and any uppercase letter (to match R & D)
        (?:                 # First non-capture group opening
            (?:             # Second non-capture group opening
                (?'O'{)     # Get the named opening brace
                [^{}]*      # Any non-brace
            )+              # Close of second non-capture group and repeat over as many times as necessary
            (?:             # Third non-capture group opening
                (?'-O'})    # Removal of named opening brace when encountered
                [^{}]*?     # Any other non-brace characters in case there are more nested braces
            )+              # Close of third non-capture group and repeat over as many times as necessary
        )+                  # Close of first non-capture group and repeat as many times as necessary for multiple side by side nested braces
        (?(O)(?!))          # Condition to prevent unbalanced braces
    )                       # Close capture group
)                           # Close positive lookahead

regex101 demo

(?=([A-Z]{(?:[^{}]|(?1))+}))

答案 1 :(得分:0)

我不确定单个正则表达式是否能够满足您的需求:这些嵌套的子串总是搞乱它。

一个解决方案可能是以下算法(用Java编写,但我想C#的翻译不会那么难):

/**
 * Finds all matches (i.e. including sub/nested matches) of the regex in the input string.
 * 
 * @param input
 *          The input string.
 * @param regex
 *          The regex pattern. It has to target the most nested substrings. For example, given the following input string
 *          <code>A{01B{23}45C{67}89}</code>, if you want to catch every <code>X{*}</code> substrings (where <code>X</code> is a capital letter),
 *          you have to use <code>[A-Z][{][^{]+?[}]</code> or <code>[A-Z][{][^{}]+[}]</code> instead of <code>[A-Z][{].+?[}]</code>.
 * @param format
 *          The format must follow the <a href= "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax" >format string
 *          syntax</a>. It will be given one single integer as argument, so it has to contain (and to contain only) a <code>%d</code> flag. The
 *          format must not be foundable anywhere in the input string. If <code>null</code>, <code>ééé%dèèè</code> will be used.
 * @return The list of all the matches of the regex in the input string.
 */
public static List<String> findAllMatches(String input, String regex, String format) {

    if (format == null) {
        format = "ééé%dèèè";
    }
    int counter = 0;
    Map<String, String> matches = new LinkedHashMap<String, String>();
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);

    // if a substring has been found
    while (matcher.find()) {
        // create a unique replacement string using the counter
        String replace = String.format(format, counter++);
        // store the relation "replacement string --> initial substring" in a queue
        matches.put(replace, matcher.group());
        String end = input.substring(matcher.end(), input.length());
        String start = input.substring(0, matcher.start());
        // replace the found substring by the created unique replacement string
        input = start + replace + end;
        // reiterate on the new input string (faking the original matcher.find() implementation)
        matcher = pattern.matcher(input);
    }

    List<Entry<String, String>> entries = new LinkedList<Entry<String, String>>(matches.entrySet());

    // for each relation "replacement string --> initial substring" of the queue
    for (int i = 0; i < entries.size(); i++) {
        Entry<String, String> current = entries.get(i);
        // for each relation that could have been found before the current one (i.e. more nested)
        for (int j = 0; j < i; j++) {
            Entry<String, String> previous = entries.get(j);
            // if the current initial substring contains the previous replacement string
            if (current.getValue().contains(previous.getKey())) {
                // replace the previous replacement string by the previous initial substring in the current initial substring
                current.setValue(current.getValue().replace(previous.getKey(), previous.getValue()));
            }
        }
    }

    return new LinkedList<String>(matches.values());
}

因此,在您的情况下:

String input = "tes{}tR{R{abc}aD{mnoR{xyz}}}";
String regex = "[A-Z][{][^{}]+[}]";
findAllMatches(input, regex, null);

返回:

R{abc}
R{xyz}
D{mnoR{xyz}}
R{R{abc}aD{mnoR{xyz}}}

答案 2 :(得分:0)

.Net正则表达式中的平衡组使您可以准确控制要捕获的内容,并且.Net正则表达式引擎保留组的所有捕获的完整历史记录(与仅捕获每个组的最后一次出现的大多数其他类型)不同

MSDN示例有点过于复杂。匹配nestes结构的更简单方法是:

(?>
    (?<O>)\p{Lu}\{   # Push to the O stack, and match an upper-case letter and {
    |                # OR
    \}(?<-O>)        # Match } and pop from the stack
    |                # OR
    \p{Ll}           # Match a lower-case letter
)+
(?(O)(?!))        # Make sure the stack is empty

或单行:

(?>(?<O>)\p{Lu}\{|\}(?<-O>)|\p{Ll})+(?(O)(?!))

<强> Working example on Regex Storm

在您的示例中,它还匹配字符串开头的"tes",但不要担心,我们还没有完成。

通过小幅修正,我们还可以捕捉 R{ ... }对之间的出现次数:

(?>(?<O>)\p{Lu}\{|\}(?<Target-O>)|\p{Ll})+(?(O)(?!))

每个Match都会有一个名为Group的{​​{1}},而且每个"Target"每次出现都会Group - 您只关心这些捕获

Working example on Regex Storm - 点击标签,查看 Capture

的4次捕获

另见: