开发者

split string using regex

I am trying t开发者_开发技巧o 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 + "\"");
}


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 /


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜