2

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 + "\"");
}
1
  • Are you trying to get individual colors or just the last color? Commented Mar 4, 2011 at 4:56

3 Answers 3

3

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 /
Sign up to request clarification or add additional context in comments.

2 Comments

+1. Or, if you really have to retain the slash at the end of the first token, you can use (?<=/(?=[^/]*$)) instead. :D
@Alan: You are right..looks like OP wants to have the / at the end.
1

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 + "\"");
}

1 Comment

I think OP wanted the string split into exactly two parts, with the split at the last /. You'd have to join all but the last part back together with / to get what was required.
1

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.