Search code examples
javaregexstringmatchpatternsyntaxexception

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


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...


Solution

  • The pattern should be

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