[英]how to get the array of strings that are inside curly braces in the source string in java
java中有一个字符串对象,其内容为:
String sourceString="This {is} a sample {string} that {contains} {substrings} inside curly {braces}";
我希望字符串数组的内容为: {is},{string},{contains},{substrings}{braces}
以下是我为获得结果而编写的代码,但我得到的输出是:
"{is} a sample {string} that {contains} {substrings} inside curly {braces}"
所以,基本上它是在第一个打开的花括号和最后一个花括号之间的所有字符。
// Source string
String sourceString="This {is} a samle {string} that {contains} {substrings} inside curly {braces}";
// Regular expression to get the values between curly braces (there is a mistake, I guess)
String regex="\\{(.*)\\}";
Matcher matcher = Pattern.compile(regex).matcher(sourceString);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
一点点谷歌搜索找到了这个解决方案,它给了我关于模式的想法
有一些时间用于Lesson:Regular Expressions带来了我需要提供这个示例的库和功能......
String exp = "\\{(.*?)\\}";
String value = "This {is} a samle {string} that {contains} {substrings} inside curly {braces}";
Pattern pattern = Pattern.compile(exp);
Matcher matcher = pattern.matcher(value);
List<String> matches = new ArrayList<String>(5);
while (matcher.find()) {
String group = matcher.group();
matches.add(group);
}
String[] groups = matches.toArray(new String[matches.size()]);
System.out.println(Arrays.toString(groups));
哪个输出
[{is}, {string}, {contains}, {substrings}, {braces}]
这是一线解决方案:
String[] resultArray = str.replaceAll("^[^{]*|[^}]*$", "").split("(?<=\\})[^{]*");
这通过首先剥离前导和尾随垃圾,然后拆分}
和{
之间的所有内容来实现。
这是一些测试代码:
String str = "This {is} a samle {string} that {contains} {substrings} inside curly";
String[] resultArray = str.replaceAll("^[^{]*|[^}]*$", "").split("(?<=\\})[^{]*");
System.out.println(Arrays.toString(resultArray));
输出:
[{is}, {string}, {contains}, {substrings}]
{characters}
可能看起来像\\\\{[^}]*\\\\}
。 Pattern
和Matcher
类,您可以找到与此正则表达式匹配的每个子字符串。 List<String>
yourList.toArray(newStringArray)
方法将其转换为数组。 更新后编辑
你的正则表达式的问题是*
量词是贪婪的,这意味着它会试图找到最大可能的解决方案。 因此,在\\\\{(.*)\\\\}
,它将匹配
{
, 最后可能}
以防万一
This {is} a samle {string} that {contains} {substrings} inside curly {braces}
意味着它将从{braces}
{
in {is}
和finis in }
开始
要使*
找到可用于创建匹配子字符串的最小字符集,您需要
?
制作完成后*?
量词不情愿, }
从可能的匹配之间{
和}
所以,与其匹配其代表任意字符.
使用[^}]
表示除}
之外的任何字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.