简体   繁体   English

JAVA在特定char的第一个和最后一个出现之间获取字符串

[英]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: 你可以使用普通的String方法在没有正则表达式的情况下做同样的事情:

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('}'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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