Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to convert regex to a java compatible regex?

Tags:

java

regex

I have a regex defined in Python/Ruby/PHP that is like this

"(forumdisplay.php\?.*page=%CURRENTPAGE%)"

When I do it for Java, I have to double escape that question mark to \\?

Like so:

"(forumdisplay.php\\?.*page=%CURRENTPAGE%)";

Is there a function I can use to do that automatically? Or would I need to change all my regexes over to work with the Java regex engine?

like image 751
James Avatar asked May 31 '10 20:05

James


People also ask

What type of regex does Java use?

The Java regex package implements a "Perl-like" regular expressions engine, but it has some extra features like possessive quantifiers ( . *+ ) and variable-length (but finite) lookbehind assertions). On the other hand, it misses a few features Perl has, namely conditional expressions or comments.

Is Java and JavaScript regex same?

There is a difference between Java and JavaScript regex flavors: JS does not support lookbehind. A tabulation of differences between regex flavors can be found on Wikipedia. However, this does not apply to your case. I surmise that your JS test string has spurious characters, eg.

What does \\ mean in Java regex?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


1 Answers

Try this online tool out https://www.regexplanet.com/advanced/java/index.html

It takes your normal regular expression and outputs the Java-compatible string expression. Saved me tons of time converting huge regex strings myself.

Note that not all regex expressions work in java. I've seen weird PHP validation regex that simply behaves differently in java pattern matching.

like image 162
Eric Chen Avatar answered Sep 17 '22 21:09

Eric Chen