-2

Below are three strings. Each string has some characters inside the brackets. I want to save those characters which are inside the brackets in some other variables. Can somebody suggest the possible ways to do this?

String name_and_code1 = "MountainBlues(MB)"; 
String name_and_code2 = "Rock(RoRo)Roll";
String name_and_code3 = "(TFT)TitForTat";
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Saroj
  • 31
  • 7

4 Answers4

2

You can make use of indexOf(). First, find the indices of '(' and ')' and then use substring(). Something like:

int start = myString.indexOf('(');
int end = myString.indexOf(')');
String result = myString.substring(start+1, end); 
//start+1 because we don't want the '('
Ivan Kukic
  • 425
  • 4
  • 14
2

Using a regular expression:

String a = "MountainBlues(MB)";
Matcher matcher = Pattern.compile("\\((.+)\\)").matcher(a);
matcher.find();
System.out.println(matcher.group(1));

prints MB

f1sh
  • 11,489
  • 3
  • 25
  • 51
1
String insideBrackets(String input){
    String result = "";
    boolean bracket = false;
    for(int i = 0: i < input.length(); i++){
        if(!bracket && input.charAt(i) == '('){
            bracket = true;
        }
        if(bracket && input.charAt(i) == ')'){
            bracket = false;
        }
        if(bracket){
            result += input.charAt(i);
        }
    }
    return result;
}

i think this should work. if it doesnt tell me right away

Alan
  • 949
  • 8
  • 26
  • Maybe use a `StringBuilder` as string concatenation in loops will produce a lot of garbage intermediate objects – Lino Feb 19 '19 at 13:51
  • maybe. but this smells like homework and i dont think they even touched stringbuilder yet. idk – Alan Feb 19 '19 at 13:53
  • 1
    Well if you already provide their homework, you should do it the correct way in the first place, but this way they learn probably nothing and just copy paste it. *shrug* – Lino Feb 19 '19 at 13:55
  • well that sure as hell is =true. – Alan Feb 19 '19 at 13:57
0

You can use regular expression for this:

Pattern p = Pattern.compile(".*(\\(.*\\)).*");
Matcher m = p.matcher("mytext(with)parentheses");

if(m.matches()) {
    String inner = m.group(1); // now inner contains "(with)" (without quotes)
    //...
}
spi
  • 1,673
  • 13
  • 19