简体   繁体   中英

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

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 > -1 && end > start) {
    System.out.println(s.substring(start, end));
}

你可以简单地使用带有参数indexOf('{')lastIndexOf('}') substring()方法,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM