[英]Regular Expression for matching parentheses
What is the regular expression for matching '(' in a string?匹配字符串中的 '(' 的正则表达式是什么?
Following is the scenario :以下是场景:
I have a string我有一个字符串
str = "abc(efg)";
I want to split the string at '('
using regular expression.For that i am using我想使用正则表达式在'('
处拆分字符串。为此,我正在使用
Arrays.asList(Pattern.compile("/(").split(str))
But i am getting the following exception.但我收到以下异常。
java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
Escaping '('
doesn't seems to work.转义'('
似乎不起作用。
Two options:两种选择:
Firstly, you can escape it using a back slash -- \\(
首先,你可以使用一个反斜杠它- \\(
Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]
或者,由于它是单个字符,您可以将它放在一个字符类中,不需要对其进行转义 -- [(]
(
with the pattern \\(
.您可以使用反斜杠转义任何元字符,以便您可以匹配(
与模式\\(
。Regex.Escape
or Java's Pattern.quote
许多语言都带有内置的转义函数,例如,.Net 的Regex.Escape
或 Java 的Pattern.quote
\\Q
and \\E
, with literal text between them.一些风格支持\\Q
和\\E
,它们之间有文字文本。(
literally, and require \\(
for capturing groups.某些风格(例如 VIM)匹配(
字面意思,并且需要\\(
来捕获组。See also: Regular Expression Basic Syntax Reference另请参阅:正则表达式基本语法参考
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:用Java 8的风格来写,可以这样解决:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
I hope it is clear.我希望很清楚。
For any special characters you should use '\\'.对于任何特殊字符,您应该使用“\\”。 So, for matching parentheses - /\\(/因此,对于匹配括号 - /\\(/
因为(
在正则表达式中是特殊的,你应该在匹配时将它转义\\(
。但是,根据你使用的语言,你可以很容易地匹配(
使用字符串方法,如index()
或其他方法,使你能够找到在什么位置(
在。有时,不需要使用正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.