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}]