gpt4 book ai didi

java - 如何在java中获取源字符串中大括号内的字符串数组

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:46:54 25 4
gpt4 key购买 nike

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

最佳答案

发现了一些谷歌搜索 this解决方案,它给了我关于模式的想法

花一些时间在 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}]

关于java - 如何在java中获取源字符串中大括号内的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21845294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com