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";
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(")"));
You can use Regex.
Matcher matcher = Pattern.compile("(state)(\(.*?\))").matcher(text);
String state = matcher.group(2);
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(")"));
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);
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);
来源:https://stackoverflow.com/questions/16764314/how-to-use-substring-and-indexof-for-a-string-with-repeating-characters