正则表达式捕获不成对的括号或圆括号

Regex to capture unpaired brackets or parentheses

如标题所示,我如何使用正则表达式捕获不成对的括号或圆括号,准确地说,在 java 中,是 java 的新手。例如,假设我有以下字符串;

Programming is productive, (achieving a lot, and getting good results), it is often 1) demanding and 2) costly.

如何捕获 1) 和 2)。 我试过:

([^\(\)][\)])

但是,我得到的结果包括如下的 s),而不是 1) 和 2):

s), 1) and 2)

我查了link:Regular expression to match balanced parentheses,但是,这个问题好像是指递归或嵌套结构,这和我的情况很不一样。 我的情况是匹配右括号或右括号,以及任何没有关联左括号或括号的关联文本。

也许,

\b\d+\)
我想

可能只是 return 所需的输出。

Demo 1

另一种方法是查看您可能拥有的左边界,在本例中,我看到数字,然后在右大括号之前我们还有哪些其他字符,然后我们可以设计一些其他简单的表达式类似于:

\b\d[^)]*\) 

Demo 2

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex = "\b\d[^)]*\)";
        final String string = "Programming is productive, (achieving a lot, and getting good results), it is often 1) demanding and 2) costly.\n\n"
             + "Programming is productive, (achieving a lot, and getting good results), it is often 1a b) demanding and 2a a) costly.\n\n\n"
             + "Programming is productive, (achieving a lot, and getting good results), it is often 1b) demanding and 2b) costly.\n\n"
             + "It is not supposed to match ( s s 1) \n";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }


    }
}

输出

Full match: 1)
Full match: 2)
Full match: 1a b)
Full match: 2a a)
Full match: 1b)
Full match: 2b)
Full match: 1)

正则表达式电路

jex.im 可视化正则表达式:

这不是正则表达式解决方案(很明显),但我想不出一个好的方法。这只是使用堆栈来跟踪括号。

对于输入字符串"(*(**)**) first) second) (**) (*ksks*) third) ** fourth)( **)

它打印出

first)
second)
third)
fourth)

所有其他括号都被忽略,因为它们是匹配的。

      String s =
            "(*(**)**) first) second) (**) (*ksks*) third) ** fourth)( **)";
      Pattern p;
      List<String> found = new ArrayList<>();
      Stack<Character> tokens = new Stack<>();
      int pcount = 0;

      for (char c : s.toCharArray()) {
         switch (c) {
            case ' ':
               tokens.clear();
               break;
            case '(':
               pcount++;
               break;
            case ')':
               pcount--;
               if (pcount == -1) {
                  String v = ")";
                  while (!tokens.isEmpty()) {
                     v = tokens.pop() + v;
                  }
                  found.add(v);
                  pcount = 0;
               }
               break;
            default:
               tokens.push(c);
         }
      }
      found.forEach(System.out::println);

注意:将方括号 (]) 集成到上面将是一个挑战(尽管并非不可能),因为人们需要检查 ( [ ) ] 之类的结构,但不清楚如何解释它。这就是为什么在指定此类要求时需要准确地拼写出来的原因。