How to get an array of strings that are inside curly brackets in the source string in java

There is a string object in java with its contents:

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

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

Below is the code that I wrote to get the result, but the output that I get:

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

So basically it takes all the characters between the first open curly braces and the 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));
}
+3
source share
3 answers

Several googling found this solution that gave me ideas for a template

, 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}]
+5

:

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}]
+1
  • , {characters}, \\{[^}]*\\}.
  • , Pattern Matcher, , .
  • List<String>
  • , , yourList.toArray(newStringArray).

, * , , . \\{(.*)\\}

  • {,
  • },

    This {is} a samle {string} that {contains} {substrings} inside curly {braces}
    

, { {is} } {braces}

* , ,

  • ? , *? ,
  • Describe your regular expression in the same way as I do, and exclude }from a possible match between {and }, so instead of matching any characters that represent ., use [^}]that represents any character except }.
0
source

All Articles