user234194
user234194

Reputation: 1723

split string using regex

I am trying to use split() to get this output:

Colour = "Red/White/Blue/Green/Yellow/"
Colour = "Orange"

...but could not succeed. What am I doing wrong?

Basically I am matching the last / and splitting the string there.

String pattern = "[\\/]$";
String colours = "Red/White/Blue/Green/Yellow/Orange";

Pattern splitter = Pattern.compile(pattern);
String[] result = splitter.split(colours);

for (String colour : result) {
    System.out.println("Colour = \"" + colour + "\"");
}

Upvotes: 2

Views: 1927

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234795

How about:

int ix = colours.lastIndexOf('/') + 1;
String[] result = { colours.substring(0, ix), colours.substring(ix) };

(EDIT: corrected to include trailing / at end of first string.)

Upvotes: 1

codaddict
codaddict

Reputation: 454950

You need to split the string on the last /. The regex to match the last / is:

/(?!.*/)

See it on IdeOne

Explanation:

/       : A literal /
(?!.*/) : Negative lookahead assertion. So the literal / above is matched only 
          if it is not followed by any other /. So it matches only the last /

Upvotes: 3

Mohamed Mansour
Mohamed Mansour

Reputation: 40149

Your pattern is incorrect, you placed the $ that says it must end with a /, remove $ and it should work fine.

While we are at it, you could just use the String.split

String colours = "Red/White/Blue/Green/Yellow/Orange";
String[] result = colours.split("\\/");

for (String colour : result) {
    System.out.println("Colour = \"" + colour + "\"");
}

Upvotes: 1

Related Questions