Java Regexs: unexpected char: '('
Question
I am using processing 1.0.6, which runs on java 1.6. I have the following code:
Pattern pattern = Pattern.compile("func\((.*),(\-?[0-9\.]*),(\-?[0-9\.]*),(\-?[0-9\.]*)\)");
but it gives the error:
unexpected char: '('
and highlights the line I pasted above. If I change the offending \(
to another character like #
, it complains of the \-
saying unexpected char: '-'
. I should be able to use literals in a regex engine and it works in C#!
Solution
You need to escape the backslashes too:
"func\\((.*),(-?[0-9.]*),(-?[0-9.]*),(-?[0-9.]*)\\)"
That string expression will the be evaluated to:
func\((.*),(-?[0-9.]*),(-?[0-9.]*),(-?[0-9.]*)\)
And that’s what you wanted.
OTHER TIPS
You have to escape \ in strings in Java by preceding it with a \, so
Pattern pattern = Pattern.compile("func\\((.*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*)\\)");
should work.
In Java '(' and '-' is not an escape-required character. So '(' means '\' without any escape-required character that is why the error occur. The solution to this is the escepe that back-slash too:
Pattern pattern = Pattern.compile("func\\((.*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*)\\)");
If you need to use RegEx in both Java and C#, perhaps you should write a program that swap from one to another.
I think you should replace "\"
with "\\"
Pattern pattern = Pattern.compile("func\\((.*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*)\\)");