在字符串中匹配'('的正则表达式是什么?
以下是场景:
我有一个字符串
str = "abc(efg)";
Run Code Online (Sandbox Code Playgroud)
我想'('
用正则表达式拆分字符串.对于我正在使用的
Arrays.asList(Pattern.compile("/(").split(str))
Run Code Online (Sandbox Code Playgroud)
但我得到以下例外.
java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
Run Code Online (Sandbox Code Playgroud)
逃避'('
似乎不起作用.
解决方案包括匹配左括号和右括号的正则表达式模式
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);
}
Run Code Online (Sandbox Code Playgroud)
用Java 8的风格写,这可以这样解决:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
我希望很清楚。
(
与pattern
匹配\(
。 Regex.Escape
或Java。Pattern.quote
\Q
和\E
,并且它们之间有文字文本。(
从字面上匹配,并且需要\(
捕获组。另请参见:正则表达式基本语法参考