Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this Regular Expression?

In java, I'm trying to detect strings of the form: optional underline, capital letters, and then curly brackets encasing two parameters. I.e. things like MAX{1,2} FUNC{3,7} _POW{9,10}

I've decided to put off dealing with the parameters until later, so the regex I'm using is:

_?[A-Z]+//{.*//}

But I'm getting the following error when trying to compile it into a Pattern object:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 9
_?[A-Z]+//{.*//}
         ^

Anyone know what the problem is?

like image 748
Moshe Avatar asked Apr 02 '11 16:04

Moshe


2 Answers

You need to escape the curly brackets in your expression, else they are treated as a repetition operator. I think you'd want to use \ for this instead of //.

like image 185
John Zwinck Avatar answered Oct 04 '22 22:10

John Zwinck


John is correct. But you also don't want to use the '.*' greedy-dot-star. Here is a better regex:

Pattern regex = Pattern.compile("_?[A-Z]+\\{[^}]+\\}");

Note that you do NOT need to escape the curly brace inside a character class. This is fundamental syntax which you need to learn if you want to use regex effectively. See: regular-expressions.info - (an hour spent here will pay for itself many times over!)

like image 44
ridgerunner Avatar answered Oct 04 '22 21:10

ridgerunner