假设我有这个字符串:
mystring
{
a : 1
b : 2
c : { e :f}
d : x
}
我该怎么做才能只得到第一个左大括号和最后一个大括号之间的字符串
因此:
a : 1
b : 2
c : { e :f}
d : x
最佳答案
默认情况下,搜索是贪婪的。您需要非贪婪地找到您的第一个 {
(.*?
),而捕获应该再次贪婪地完成 (.*
):
".*?\{(.*)\}.*"
完整代码为:
String s = // your input string
Pattern p = Pattern.compile(".*?\\{(.*)\\}.*");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(1));
}
你也可以在没有正则表达式的情况下做同样的事情,使用普通的 String
方法:
int start = s.indexOf("{") + 1;
int end = s.lastIndexOf("}");
if (start > 0 && end > start) {
System.out.println(s.substring(start, end));
}
关于JAVA获取特定字符第一次出现和最后一次出现之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711880/