문제

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?

도움이 되었습니까?

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top