gpt4 book ai didi

java - 使用正则表达式拆分字符串

转载 作者:行者123 更新时间:2023-11-30 06:36:09 25 4
gpt4 key购买 nike

我正在尝试使用 split() 来获得此输出:

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

...但无法成功。我做错了什么?

基本上我匹配最后一个 / 并在那里拆分字符串。

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

最佳答案

您需要在最后 / 处拆分字符串。匹配最后一个 / 的正则表达式是:

/(?!.*/)

See it on IdeOne

解释:

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

关于java - 使用正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com