java - 使用正则表达式拆分字符在java中返回一个空值

标签 java regex string

这是我的意见

....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-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

但是,如果找到前导空元素,则将包括在内。因此,我们首先需要去掉字符串开头的那些分隔符。

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

相关文章:

java - notifyDataSetChanged 不适用于 fragment

java - 调试 'Detail Formatters' 如何解析 eclipse 中的类?

Java正则表达式否定前瞻错误匹配

javascript - JS判断String是否有电话号码

python - 用于匹配 "01.0 to 60.0 in steps of 0.5, or 99.9"的正则表达式?

c - 字符串反转而不改变原始字符串

带有行尾的 C++ 字符串用于归档空行

java - Class.forName 返回 null

java - HashSet<HashSet<int>> 在 Java 中不允许重复,但在 C# 中允许

将 C 中的字符串文字复制到字符数组中