Reputation: 89179
I would like someone to help me to rectify my regular expression to split this string:
{constraint.null.invalid}{0,1,2}
Basically, I want anything inside {
and }
, so my output must be:
constraint.null.invalid
0,1,2
.My regular expression, which I've tried closely is:
\{([\S]+)\}
But the value I get is:
constraint.null.invalid}{0,1,2
What am I missing?
Sample code:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\{([\\S]+)\\}", Pattern.MULTILINE);
String test = "{constraint.null.invalid}{0,1,2}";
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
Thanks
PS: The string can contain values bounded by 1 or more {
and }
.
Upvotes: 1
Views: 1887
Reputation: 16037
a little different approach, with this pattern "\{([^\{\}]*)\}"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReTest {
/**
* @param args
*/
public static void main(String[] args) {
String s = "bla bla {constraint.null.invalid} bla bla bla {0,1,2} bla bla";
Pattern p = Pattern.compile("\\{([^\\{\\}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()){
System.out.println(m.group(1));
}
}
}
Upvotes: 2
Reputation:
The +
quantifier is greedy. Use +?
for the reluctant version.
See http://docs.oracle.com/javase/tutorial/essential/regex/quant.html for details.
Upvotes: 4