java 提取字符串中大括号的值,如何获取java中源字符串中大括号内的字符串数组...

There is a string object in java with its contents as:

String sourceString="This {is} a sample {string} that {contains} {substrings} inside curly {braces}";

I want the array of string with its contents as: {is},{string},{contains},{substrings}{braces}

Following is the code that I wrote to get the result but the output I am getting is:

"{is} a sample {string} that {contains} {substrings} inside curly {braces}"

So, basically it is taking all the characters that are in between the first open curly braces and last closing 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));

}

解决方案

A little bit of Googling found this solution, which gave me ideas for the pattern

Some time spent with Lesson: Regular Expressions brought the libraries and functionality I would need to provide this example...

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 matches = new ArrayList(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));

Which outputs

[{is}, {string}, {contains}, {substrings}, {braces}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值