简体   繁体   English

使用正则表达式分割字符串

[英]split string using regex

I am trying to use split() to get this output: 我正在尝试使用split()获得以下输出:

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 在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 /

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.) (编辑:更正为在第一个字符串的末尾包含尾随/ 。)

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM