Question

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?

Was it helpful?

Solution 2

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("\\.");

OTHER TIPS

Use "\\." instead. Just using . means 'any character'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top