Tito
Tito

Reputation: 178

JAVA get string between first and last occurence of a particular char

Assuming I have this string:

mystring
{
    a : 1
    b : 2
    c : { e :f}
    d : x
}

How do I do it such that I will get only the string between the first opening curly-bracket and the last opening curly bracket

As such :

    a : 1
    b : 2
    c : { e :f}
    d : x

Upvotes: 2

Views: 2095

Answers (2)

vlumi
vlumi

Reputation: 1319

By default the search is done greedily. You need to find your first { non-greedily (.*?), while the capture should be done again greedily (.*):

".*?\{(.*)\}.*"

The full code would be:

String s = // your input string
Pattern p = Pattern.compile(".*?\\{(.*)\\}.*");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group(1));
}

You could do the same thing without regex, too, using plain String methods:

int start = s.indexOf("{") + 1;
int end = s.lastIndexOf("}");
if (start > 0 && end > start) {
    System.out.println(s.substring(start, end));
}

Upvotes: 5

Shaik Bajivali
Shaik Bajivali

Reputation: 167

you can simply use substring() method with parameters indexOf('{') and lastIndexOf('}') as below:

yourString=yourString.substring(indexOf('{'),lastIndexOf('}'));

Upvotes: 1

Related Questions