user3078555
user3078555

Reputation:

Java expression for Embedded parameter

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

Answers (2)

m0skit0
m0skit0

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

Mena
Mena

Reputation: 48404

There are a few issues with your Pattern.

  • Firstly you don't need the outer parenthesis, as you're not defining a group save from the main group.
  • Secondly you must escape the curly brackets (\\{), otherwise they will be interpreted as a quantifier.
  • Thirdly you don't need the last quantifier (*), as you're iterating over matches within the same input String

So your Pattern will look something like "\\{\\d+\\}".

More info on Java Patterns 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

Related Questions