0

I want to split a String by dot (".") in Java and I know that the split function of String in Java use regular expression, so I used someString.split("\.") to escape the special character ".", but it didn't work; I tried someString.split("\\.") and it worked.

I used split("\t") before to split String with tab and it worked. Why that it's not necessary to escape the special character '\t' like split("\\t")?

Tom
  • 16,842
  • 17
  • 45
  • 54
  • @ErwinBolwidt: Thanks for reminding me. So many languages, so many *slightly* different rules... :-) – T.J. Crowder Apr 18 '17 at 01:00
  • See the linked questions' answers for details, but re the dichotomy between `"\."` and `"\t"`, it's because in a string literal, `\.` is an invalid escape sequence, whereas in a string literal, `\t` is a tab character. Since tab characters aren't special in a regular expression, `split("\t")` splits on tabs. To pass the backslash to the underlying regular expression (so you can escape the `.`, since it's special in a regex), you need to have an actual backslash in the string, so of course you have to escape it (`"\\."`). – T.J. Crowder Apr 18 '17 at 01:04

1 Answers1

1

The split function matches the actual String, therefore it is not necessary to escape the "\t" because you want it to be looking for the tab character, not the character sequence "\t" (Which "\\t" would achieve).