-2

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?

kaya3
  • 47,440
  • 4
  • 68
  • 97
Maurdekye
  • 3,597
  • 5
  • 26
  • 43
  • I wonder how this compile. `split` returns an array. But to answer your question, you need to escape the `.` – Alexis C. Jan 26 '14 at 22:09
  • You might also use `[.]` since the dot will lose it's (regex) meaning in a character class. – HamZa Jan 26 '14 at 22:43

2 Answers2

5

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

AntonH
  • 6,359
  • 2
  • 30
  • 40
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("\\.");
aliteralmind
  • 19,847
  • 17
  • 77
  • 108