gpt4 book ai didi

java - 如何使用 Java Regex 将特定字符串放入数组?

转载 作者:行者123 更新时间:2023-11-29 05:47:00 25 4
gpt4 key购买 nike

如何在Java中用正则表达式将下面的“no”、“no”、“0.002”、“0.998”放入String数组中?

 String lines = "     1       2:no       2:no       0.002,*0.998"

有人能告诉我下面的“theRegex”怎么写吗?

String[] matches = lines.split(theRegex); // => ["no", "no", "0.002", "0.998"]

在 Python 中,它只是一行:

matches = line =~ /\d:(\w+).*\d:(\w+).*\((\w+)\)/

但是 Java 呢?

最佳答案

theRegex="[\\s,*]+"(一个或多个空格、逗号或星号)

输入 1 2:no 2:no 0.002,*0.998输出 ["1","2:no","2:no","0.002","0.9"]

编辑

The input String is " 1 2:no 2:no 0.002,*0.998", and the expected output is ["no", "no", "0.002", "0.998"]

在这种情况下,不可能单独使用 split,因为要忽略 1,您需要将 \d 视为分隔符,但是 \d 也是 0.002 中数据的一部分。

你可以做的是:

   Pattern pattern = Pattern.compile("^\\d(?:$|:)");
String[] matches = lines.trim().split("[\\s,*]+");
List<String> output = new LinkedList<String>(Arrays.asList(matches));
for (Iterator<String> it=output.iterator(); it.hasNext();) {
if (Pattern.matcher(it.next()).find()) it.remove();
}

find("^\\d(?:$|:") 匹配 digitdigit:whatever 形式的字符串。请注意,该模式编译一次,然后应用于列表中的字符串。对于每个字符串,必须构造一个匹配器。

关于java - 如何使用 Java Regex 将特定字符串放入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15502460/

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