[英]Extract string between curly braces in java
我有 String {a,b,c},{1,2,3}
。 如何提取以获得喜欢
String1 = a,b,c;
String2 = 1,2,3;
我尝试过这样的事情,但这不起作用。
String result1 = str.substring(str.indexOf("{") + 1, str.indexOf("},"));
String result2 = str.substring(str.indexOf(",{") + 1, str.indexOf("}"));
有一个indexOf
方法可以获取要搜索的索引
String str = "{a,b,c},{1,2,3}";
int startingIndex = str.indexOf("{");
int closingIndex = str.indexOf("}");
String result1 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result1);
startingIndex = str.indexOf("{", closingIndex + 1);
closingIndex = str.indexOf("}", closingIndex + 1);
String result2 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result2);
在第二个块中,我们从closingIndex + 1
开始搜索,其中closingIndex
是最后看到的}
的索引。
您可以使用正则表达式,例如
Matcher m = Pattern.compile("(?<=\\{).+?(?=\\})").matcher("{a,b,c},{1,2,3}");
while(m.find()){
System.out.println(m.group());
// a,b,c
// 1,2,3
}
此任务的可能解决方案之一是使用Pattern 类。
在大括号之间获取值应该是一个更优雅的解决方案。
为了匹配第一组正则表达式应该是: \\{([^}]*)\\}
。
只需在 group 之间添加一个分隔符,
然后再次重复正则表达式。 现在您可以单独获得结果。
下面是代码演示:
public class RegexDemo {
public static void main(String[] args) {
String str = "{a,b,c},{1,2,3}";
Pattern pattern = Pattern.compile("\\{([^}]*)\\},\\{([^}]*)\\}");
Matcher matcher = pattern.matcher(str);
String first = null;
String second = null;
if (matcher.find()) {
first = matcher.group(1);
second = matcher.group(2);
}
System.out.printf("First: %s\nSecond: %s\n", first, second);
}
}
输出:
First: a,b,c
Second: 1,2,3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.