Easy way to convert regex to a java compatible regex?
I have a开发者_Go百科 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?
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.
Note that this is not the Java regular expression engine that requires the double backslashes, but the Java compiler. When you write the following in Java source code:
"(forumdisplay.php\\?.*page=%CURRENTPAGE%)"
the Java compiler interprets this as the string:
(forumdisplay.php\?.*page=%CURRENTPAGE%)
The Java regular expression engine then does exactly the same thing as other regular expression engines - the question mark (because it is escaped) is treated literally.
A similar thing happens in Python - the two strings below are identical:
r"(forumdisplay.php\?.*page=%CURRENTPAGE%)"
"(forumdisplay.php\\?.*page=%CURRENTPAGE%)"
This is using the Python r
notation for a "raw" string where backslashes are not interpreted by the compiler.
Personally I use within Eclipse the EXCELLENT plugins from the site http://www.bastian-bergerhoff.com/eclipse/features/
You will find there QuickREx for regular expression and also XPath developper plugin that I use a lot.
For QuickREx, just test you regular expression and press the button to copy it on your active editor with the good escapes characters.
It's a must, just give it a try.
A good start is usually to just do a "find replace all" of "\" with "\\".
You aren't really doing a change to make this work with the java regex engine. You are just having to deal with the pains of storing a regex in a Java String... You could do this in a function, but that would make more code to maintain. I would suggest doing a find replace as described above...
精彩评论