Split the string between two

Asked

Viewed 47 times

0

I’m trying to split by \ from the string below, I just wanted to pick up Yorktown, but I’m not getting it.

\Locations\North America\US Mid-Hudson Valley\Yorktown\Yorktown Heights\

My code is like this:

String[] locationCategory1 = row.getCell(0).getStringCellValue().split("/[\\.]/");
             String locationCategory1splited = locationCategory1[4];

1 answer

1


Some languages require a regex to be between delimiters, with / the most common. But nay is the case of Java, you do not need to put the bars at the beginning and end. When putting them, the split will attempt to search for the character itself /.

Another detail is that [\\.] actually corresponds to the character ., then your regex is searching for a bar, followed by a dot, followed by another bar.

If the idea is to separate by \, just put this character. One annoying detail is that it is used in regex to make the escape of meta characters and for it to be interpreted as the character itself \, you need to write it as \\.

Only in a Java string, "\\" results in only one \, then the regex has to be written as \\\\ (this becomes the regex \\, which corresponds to the character \). Thus:

String s = "\\Locations\\North America\\US Mid-Hudson Valley\\Yorktown\\Yorktown Heights\\";
System.out.println(s.split("\\\\")[4]);

The code output above is "Yorktown".

  • Thank you so much! It worked!!

  • 1

    hkotsubo king of the regex

Browser other questions tagged

You are not signed in. Login or sign up in order to post.