views:

223

answers:

4

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#!

+4  A: 

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.

Gumbo
Does java have something similar to C#'s @"literal string" notation?
Callum Rogers
C Rogers: no. As an aside: could MS have picked a worse name for that notation? "Literal string" as opposed to an ordinary "string literal". Ugh.
Laurence Gonsalves
My mistake, they are called "string literals".
Callum Rogers
Looks like they're actually called "verbatim string literals" (as opposed to regular string literals). Sorry MS: that name isn't too bad after all.
Laurence Gonsalves
A: 

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.

Elmar Weber
A: 

I think you should replace "\" with "\\"

Pattern pattern = Pattern.compile("func\\((.*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*),(\\-?[0-9\\.]*)\\)");
Oleg
A: 

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.

NawaMan
I've just recently moved from C# to Java (due to the excellent http://www.processing.org/ framework), so I am still getting used to the grammar/functionality changes.
Callum Rogers