匹配括号的正则表达式

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

情况如下:

我有根绳子

str = "abc(efg)";

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

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

但我得到了下面的例外。

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

逃离 '('似乎没有用。

229648 次浏览

For any special characters you should use '\'. So, for matching parentheses - /\(/

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

The solution consists in a regex pattern matching open and closing parenthesis

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);
}

Writing in Java 8's style, this can be solved in this way:

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

I hope it is clear.