Java: PatternSyntaxException thrown with regex .*-\\d+{.*}\\d+-.*

736 Views Asked by At

I am trying to make a regex to determine if a String contains a -, some amount of digits, a {, nothing/some sequence of characters, a }, some amount of digits, and a final -. For example:

gibberish-345{randomtext}938475-moregibberish

^&*^%^asdf-9897689{symbols$%&*}456-h6

-456{}456-

I have tried using String.matches("*-\\d+{.*}\\d+-.*") and String.matches("*-[\\d]+{.*}[\\d]+-.*"), but in each case I get a PatternSyntaxException (both of them are below):

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 5
.*-\d+{.*}\d+-.*
 ^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.closure(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.matches(Unknown Source)
at java.lang.String.matches(Unknown Source)
at conv.Congine.qual(Congine.java:17)
at conv.Congine.convert(Congine.java:5)
at conv.Main.main(Main.java:6)

~

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 7
.*-[\d]+{.*}[\d]+-.*
   ^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.closure(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.matches(Unknown Source)
at java.lang.String.matches(Unknown Source)
at conv.Congine.qual(Congine.java:17)
at conv.Congine.convert(Congine.java:5)
at conv.Main.main(Main.java:6)

Am I using a regex symbol that I don't know I'm using? I've checked, but I don't think that -, {, or } qualifies as a regex symbol...

4

There are 4 best solutions below

0
On BEST ANSWER

The pattern should be

.*-\\d+\\{.*\\}\\d+-.*
1
On

It looks like I can answer my own question... apparently { and } are special characters in regex, you have to escape them with \\. Oh well.

0
On
String.matches("*-\\d+\\{.*}\\d+-.*");

It's mainly because of the { character next to the + symbol. We all know, in regex, + repeats the previous token one or more times where as the repetition quantifier {start,end} repeats the previous token according to the range given inside the {} curly braces. So the regex engine considers the { as the start of the repetition quantifier and + before the { causes this to fail. We can't specify o+{2} but we do (o+){2}. And also you don't need to escape the closing curly bracket.

0
On

The pattern will be:

^.*[-]\\d+\\{.*\\}\\d+[-].*$

Thanks,