这是我的意见
....ALPO..LAPOL.STRING
我想在到达“.”时将每个字符串分开并存储在字符串数组列表中。
我尝试使用下面的代码,
ArrayList<String> words = new ArrayList<> (Arrays.asList(chars.stream().map(String::valueOf)
.collect(Collectors.joining("")).split("\\.+")));
正则表达式 split("\.+")) 有问题。
预期输出:
阿尔普
洛杉矶
字符串
实际输出:
""-> 空格
洛杉矶
字符串
它将列表的第一个值打印为空值,因为有很多 '.'在“A”之前出现。如何摆脱字符串数组列表中的这个空值。任何帮助都会很高兴!!
最佳答案
出现空元素是因为分隔符在您需要获取的第一个值之前匹配。
您需要先使用 .replaceFirst("^\\.+", "")
删除字符串开头的分隔符,然后拆分:
String results[] = "....ALPO..LAPOL.STRING".replaceFirst("^\\.+", "").split("\\.+");
System.out.println(Arrays.toString(results));
参见 IDEONE demo
^\\.+
模式匹配字符串的开头 (^
),然后匹配 1 个或多个文字点 (\\.+
)。使用 replaceFirst
是因为只需要 1 个替换(不需要使用 replaceAll
)。
可以在 documentation 中找到有关 Java 拆分的更多详细信息:
public String[] split(String regex)
Splits this string around matches of the given regular expression. This method works as if by invoking the two-argumentsplit
method with the given expression and a limit argument ofzero
. Trailing empty strings are therefore not included in the resulting array.
但是,如果找到前导空元素,则将包括在内。因此,我们首先需要去掉字符串开头的那些分隔符。
关于java - 使用正则表达式拆分字符在java中返回一个空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36984000/