Pattern to extract text between parenthesis

怎甘沉沦 提交于 2019-12-17 18:27:03

问题


How to extract string from "(" and ")" using pattern matching or anything. For example if the text is `

"Hello (Java)"

Then how to get only "Java".

Thanks.


回答1:


Try this:

 String x= "Hello (Java)";
 Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
while(m.find()) {
    System.out.println(m.group(1));
}

or

String str = "Hello (Java)";
String answer = str.substring(str.indexOf("(")+1,str.indexOf(")"));



回答2:


List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher("Hello This is (Java) Not (.NET)");

while (regexMatcher.find()) {//Finds Matching Pattern in String
   matchList.add(regexMatcher.group(1));//Fetching Group from String
}

for(String str:matchList) {
   System.out.println(str);
}

OUTPUT

Java
.NET

What does \\((.+?)\\) mean?

This regular Expression pattern will start from \\( which will match ( as it is reserved in regExp so we need escape this character,same thing for \\) and (.*?) will match any character zero or more time anything moreover in () considered as Group which we are finding.




回答3:


I know this was asked 3 years ago, but for anyone with the same/similar question that lands here (as I did), there is something even simpler than using regex:

String result = StringUtils.substringBetween(str, "(", ")");

In your example, result would be returned as "Java". I would recommend the StringUtils library for various kinds of (relatively simple) string manipulation; it handles things like null inputs automatically, which can be convenient.

Documentation for substringBetween(): https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBetween-java.lang.String-java.lang.String-java.lang.String-

There are two other versions of this function, depending on whether the opening and closing delimiters are the same, and whether the delimiter(s) occur(s) in the target string multiple times.



来源:https://stackoverflow.com/questions/24256478/pattern-to-extract-text-between-parenthesis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!