-4

I want to split a String with the regex ".", but the result is strange

String position = test.image.png;
String[] split = position.split(".");

System.out.println(position);
System.out.println(split.length);
for(String element : split) System.out.println(element);

WHY the output is:

test.image.png
0


???

FoxWare
  • 14
  • 2
  • 1
    What is `test.image.png` here ? and to split by `.` you need to escape like `position.split("\\.")` – Eklavya Jun 30 '20 at 14:42
  • 1
    Does this answer your question ? https://stackoverflow.com/questions/14833008/java-string-split-with-dot – Eklavya Jun 30 '20 at 14:52
  • Does this answer your question? [Split string with dot as delimiter](https://stackoverflow.com/questions/3387622/split-string-with-dot-as-delimiter) – kaya3 Jun 30 '20 at 15:15

1 Answers1

2
String position = "test.image.png";
String[] split = position.split("\\.");

System.out.println(position);
System.out.println(split.length);
for(String element : split) System.out.println(element);

The code above will work. Why? Because you need to escape metacharacters in Java Regex with a backslash. A . (fullstop/period) is such a character. Using it without an escape, will match any character.

More info on Java Regex

Be sure to take a look at the provided link, everything's in there and easily understandable.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Paul
  • 841
  • 13
  • 20
  • Well, you have to escape dots for the regex, and escape the backslash you use to escape that. Dots are not special characters in Java strings – user Jun 30 '20 at 14:53
  • As I understood it, there are several metacharacters that need to be escaped. A point is one of them... – Paul Jun 30 '20 at 14:55
  • Yes, but my point was that your answer makes it seem like you're always supposed to escape dots in Java strings, even though the first backslash is for regex and the *second* backslash is to escape that first one. (By first backslash, I mean the one closer to the dot) – user Jun 30 '20 at 14:59
  • 1
    yes, you're correct. If you know it, it seems so simple. I'll edit the answer – Paul Jun 30 '20 at 15:04
  • That's very good of you. Could you also add that it is `.` that is a metacharacter and say what the dot does in regex normally? – user Jun 30 '20 at 15:06
  • 1
    as per request. It's oft forgotten how much the small things matter, such as providing a thorough answer. I need to keep that in mind, so thank you. – Paul Jun 30 '20 at 15:14