Reputation:
I am defining java expression for my pattern but it does not work.
Here is the text that I want to define a pattern for:
"sometext {10} some text {25} sometext".
Named parameters are {10}, {25},
....
I used pattern like this: "({\d+})*" but It doesn't work and I received exception:
Caused by: java.util.regex.PatternSyntaxException: Illegal repetition near index 0
({\d+})*
Here is the code I have:
public static final Pattern pattern = Pattern.compile("({\\d+})*");
public static void main(String[] args) {
String s = "{10}ABC{2}";
Matcher matcher = pattern .matcher(s);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
Can someone explain what I am wrong here? Thanks.
Upvotes: 1
Views: 123
Reputation: 25873
{
is a special character in regex, just double-escape it \\{
. Same for }
.
Also take into account that if you use *
, it will also match empty strings.
Upvotes: 2
Reputation: 48404
There are a few issues with your Pattern
.
\\{
), otherwise they will be interpreted as a quantifier.*
), as you're iterating over matches within the same input String
So your Pattern
will look something like "\\{\\d+\\}"
.
More info on Java Pattern
s here.
Edit -- example
String input = "sometext {10} some text {25} sometext";
Pattern p = Pattern.compile("\\{\\d+\\}");
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group());
}
Output:
{10}
{25}
Upvotes: 2