用于匹配括号的正则表达式

2022-08-31 12:22:29

在字符串中匹配 '(' 的正则表达式是什么?

场景如下:

我有一根绳子

str = "abc(efg)";

我想使用正则表达式拆分字符串。为此,我正在使用'('

Arrays.asList(Pattern.compile("/(").split(str))

但是我得到了以下例外。

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

逃避似乎不起作用。'('


答案 1

两个选项:

首先,你可以使用斜线来逃避它——\(

或者,由于它是单个字符,因此您可以将其放在字符类中,而无需对其进行转义 -[(]


答案 2

该解决方案由匹配开括号和右括号的正则表达式模式组成

String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis, 
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
   // I print first "Your", in the second round trip "String"
   System.out.println(part);
}

以Java 8的风格编写,这可以通过以下方式解决:

Arrays.asList("Your(String)".split("[\\(\\)]"))
    .forEach(System.out::println);

我希望这是清楚的。