I found a regular expression which matches tokens surrounded with {} but it only seems find the first found item.
How can the following code be changed so that all of the tokens will be found rather than just {World}, would i need to use loops?
// The search string
String str = "Hello {World} this {is} a {Tokens} test";
// The Regular expression (Finds {word} tokens)
Pattern pt = Pattern.compile("\\{([^}]*)\\}");
// Match the string with the pattern
Matcher m = pt.matcher(str);
// If results are found
if (m.find()) {
System.out.println(m);
System.out.println(m.groupCount()); // 1
System.out.println(m.group(0)); // {World}
System.out.println(m.group(1)); // World (Get without {})
}
Yes, in your code you just do one match, and get the groups captured in that single match.
If you want to get the other matches, you have to continue matching in a loop until
find()returns false.So basically all you need is to replace
ifwithwhileand you’re there.