How to use substring and indexOf for a String with repeating characters?

69,018

Solution 1

Use lastIndexOf. Also increase the initial offset to allow for the number of characters in the sub-string state(:

String state = myString.substring(myString.indexOf("state(") + 6, myString.lastIndexOf(")"));

Solution 2

You can use Regex.

Matcher matcher = Pattern.compile("(state)(\(.*?\))").matcher(text);
String state = matcher.group(2);

Solution 3

You could just cut the string down, and do it in a sanboxed piece. This way if there are more trailing ")" nothing bad happens

String state = myString.substring(myString.indexOf("state(")+6);
state = state.substring(0,state.indexOf(")"));

Solution 4

You can use other version of String#indexOf(String str, int fromIndex) to specify from what position you would like to start searching ")".

int start = myString.indexOf("state(")+6;//6 is the length of "state(" - we dont want that part
int end = myString.indexOf(")", start);
String state = myString.substring(start, end);

Solution 5

Your problem is the first occurrence of ")" is before the occurrence of "state(", as it also appears after Denver.

If you need the last index, you could use lastIndexOf(), for both "(" and ")". If you need precisely the second occurrence, you could use the version of indexOf() that lets you specify an index where to start the search, and set that index to be the one after the first occurrence of your char, Like this:

 int firstOpenP = myString.indexOf("(");
 int firstClosedP = myString.indexOf(")");
 int secondOpenP = myString.indexOf("(", firstOpenP + 1);
 int secondClosedP = myString.indexOf(")", firstClosedP + 1);
 String state = myString.substring(secondOpenP + 1, secondClosedP);
Share:
69,018
Buras
Author by

Buras

Oracle DBA

Updated on May 27, 2020

Comments

  • Buras
    Buras almost 4 years

    I have the following String myString="city(Denver) AND state(Colorado)"; It has repeating "(" and ")"...

    How can I retrieve state name, i.e. Colorado. I tried the following:

    String state = myString.substring(myString.indexOf("state(")+1,myString.indexOf(")"));
    

    But it give indexOutOfBoundException

    Is there any way to specify that I need the second "(" in myString? I need the result: String state = "Colorado";

  • Buras
    Buras almost 11 years
    Thanks it works! May i ask just in case I have this "(" repeating multiple times, e.g. myString="abc(defg(h(i(k(o". Is there any way to specify that I need the third "("? Can I use: myString.thirdIndexOf("("))...probably not?
  • Reimeus
    Reimeus almost 11 years
    In that case you would use indexOf(String, startIndex) Of course you would have to the location of the 3rd ( by getting the indices from substrings again using indexOf(String, startIndex).