49

How can I get inside parentheses value in a string?

String str= "United Arab Emirates Dirham (AED)";

I need only AED text.

4

10 回答 10

100

Compiles and prints "AED". Even works for multiple parenthesis:

import java.util.regex.*;

public class Main
{
  public static void main (String[] args)
  {
     String example = "United Arab Emirates Dirham (AED)";
     Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
     while(m.find()) {
       System.out.println(m.group(1));    
     }
  }
}

The regex means:

  • \\(: character (
  • (: start match group
  • [: one of these characters
  • ^: not the following character
  • ): with the previous ^, this means "every character except )"
  • +: one of more of the stuff from the [] set
  • ): stop match group
  • \\): literal closing paranthesis
于 2013-01-29T13:40:05.437 回答
25

i can't get idea how to split inside parentheses. Would you help highly appreciated

When you split you are using a reg-ex, therefore some chars are forbidden.

I think what you are looking for is

str = str.split("[\\(\\)]")[1];

This would split by parenthesis. It translates into split by ( or ). you use the double \\ to escape the paranthese which is a reserved character for regular expressions.

If you wanted to split by a . you would have to use split("\\.") to escape the dot as well.

于 2013-01-29T13:42:10.050 回答
23

This works...

String str = "United Arab Emirates Dirham (AED)";
String answer = str.substring(str.indexOf("(")+1,str.indexOf(")"));
于 2013-01-29T13:36:04.727 回答
19

I know this was asked over 4 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 "AED". 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.

于 2017-10-03T20:34:40.320 回答
4

You could try:

String str = "United Arab Emirates Dirham (AED)";
int firstBracket = str.indexOf('(');
String contentOfBrackets = str.substring(firstBracket + 1, str.indexOf(')', firstBracket));
于 2013-01-29T13:28:45.090 回答
2

I can suggest two ways:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args){
        System.out.println(getParenthesesContent1("United Arab Emirates Dirham (AED)"));
        System.out.println(getParenthesesContent2("United Arab Emirates Dirham (AED)"));
    }

    public static String getParenthesesContent1(String str){
        return str.substring(str.indexOf('(')+1,str.indexOf(')'));
    }

    public static String getParenthesesContent2(String str){
        final Pattern pattern = Pattern.compile("^.*\\((.*)\\).*$");
        final Matcher matcher = pattern.matcher(str);
        if (matcher.matches()){
            return matcher.group(1);
        } else {
            return null;
        }
    }
}
于 2013-01-29T13:40:49.117 回答
0

yes, you can try different techniques like using

 string.indexOf("("); 

to get the index and the use

string.substring(from, to)
于 2013-01-29T13:30:54.220 回答
0

Using regular expression:

String text = "United Arab Emirates Dirham (AED)";
Pattern pattern = Pattern.compile(".* \\(([A-Z]+)\\)");
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
    System.out.println("found: " + matcher.group(1));
}
于 2013-01-29T13:32:00.993 回答
0

The answer from @Cœur is probably correct, but unfortunately it did not work for me. I had text similar to this:

mrewrwegsg {text in between braces} njanfjaenfjie a {text in between braces}

It was way larger, but let's consider only this short part.

I used this code to get each text between bracelet and print it to the console:

Pattern p = Pattern.compile("\\{.*?\\}");
Matcher m = p.matcher(test);
while(m.find()) {
      System.out.println(m.group().subSequence(1, m.group().length()-1));
}

It might be more complicated than @Cœur answer, but maybe there is someone like me, who can find my answer useful.

于 2019-05-28T10:44:10.503 回答
0

The below method can split any String inside any bracket like '(. {. [, ), }, ]'.

public String getStringInsideChars(String original, char c){
    this.original=original;
    original = cleaning(original);
    for(int i = 0; i < original.length(); i++){
        if(original.charAt(i) == c){
            String temp = original.substring(i + 1, original.length());
            i = original.length();//end for
            for(int k = temp.length() - 1; k >= 0; k--){
                if(temp.charAt(k) == getReverseBracket(c)){
                    original = temp.substring(0, k);
                    k = -1; // end for
                }
            }
        }
    }
    return original;
}

private char getReverseBracket(char c){
    return c == '(' ? ')' :
           c == '{' ? '}' :
           c == '[' ? ']' :
           c == ')' ? '(' :
           c == '}' ? '{' :
           c == ']' ? '[' : c;
}

public String cleaning(String original) {
    this.original = original;
    return original.replaceAll(String.valueOf('\t'), "").replaceAll(System.getProperty("line.separator"), "");
}

You can use it like below :

getStringInsideChars("{here is your string}", '{')

it will return "here is your string"

于 2020-11-22T23:24:46.290 回答