Easy way to convert regex to a java compatible regex?

后端 未结 4 2080
花落未央
花落未央 2021-01-01 21:30

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

4条回答
  •  离开以前
    2021-01-01 22:18

    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.

提交回复
热议问题