gpt4 book ai didi

java - Regex/String.split 未按预期工作

转载 作者:行者123 更新时间:2023-11-29 21:49:48 25 4
gpt4 key购买 nike

我正在以这种形式接收数据,这三行中的每一行都是它自己的字符串:

   0 -rw-------    1       167 Tue Nov 13 10:39:28 2012 .bash_history
0 -rw-r--r-- 1 40 Wed Nov 28 12:18:03 2012 aaa.txt
22290 -rw-r--r-- 1 22824944 Tue Jan 15 15:05:58 2013 a.bin

我尝试使用此正则表达式将其拆分为由空格分隔的标记。

String[] tokens = newParts[i].split("\\s{1,}");

然而,这总是将前两行的第一个标记创建为空字符串,并正确地将 22290 设置为第三行的第一个标记。为什么是这样?所有其余的 token 都是我想要的。只是不是前两行中的第一行,为什么?

最佳答案

引用Pattern.split documentation :

The array returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence.

因此,如果您的字符串以分隔符开头,则您的第一个元素将为空字符串。同样,如果您的字符串以分隔符结尾,则您的最后一个元素将为空字符串。

编辑:实际上 split(string) 调用了 split(string, 0),它显式地丢弃了尾随的空元素。但它对空的起始元素没有任何作用。

如果您首先对输入调用 trim(),它应该会如您所愿地工作。

关于java - Regex/String.split 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707889/

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