Search code examples
javaregexescapingperiod

Java regex ignore '.' symbol


I'm trying to split a string at every '.' (period), but periods are a symbol used by java regexes. Example code,

String outstr = "Apis dubli hre. Agro duli demmos,".split(".");

I can't escape the period character, so how else do I get Java to ignore it?


Solution

  • I can't escape the period character, so how else do I get Java to ignore it?

    You can escape the period character, but you must first consider how the string is interpreted.

    In a Java string (that is fed to Pattern.compile(s))...

    • "." is a regex meaning any character.
    • "\." is an illegally-escaped string. This won't compile. As a regex in a text editor, however, this is perfectly legitimate, and means a literal dot.
    • "\\." is a Java string that, once interpreted, becomes the regular expression \., which is again the escaped (literal) dot.

    What you want is

    String outstr = "Apis dubli hre. Agro duli demmos,".split("\\.");