如何获取java中源字符串中大括号内的字符串数组 [英] how to get the array of strings that are inside curly braces in the source string in java

查看:1187
本文介绍了如何获取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}";

我希望字符串数组的内容为: {is}, {string},{contains},{substrings} {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<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中源字符串中大括号内的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆