java - 使用 [a-z] 正则表达式在 Java 中拆分字符串

标签 java regex

我有两个正则表达式:

[a-c] : any character from a-c

[a-z] : any character from a-z

还有一个测试:

public static void main(String[] args) {
    String s = "abcde";
    String[] arr1 = s.split("[a-c]");
    String[] arr2 = s.split("[a-z]");

    System.out.println(arr1.length); //prints 4 : "", "", "", "de"
    System.out.println(arr2.length); //prints 0 
}

为什么第二次 split 会这样?我希望有 6 个空字符串 ""结果的结果。

最佳答案

根据 the documentation of the single-argument String.split :

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.

要保留尾随字符串,您可以使用双参数版本,并指定一个负数限制:

    String s = "abcde";
    String[] arr1 = s.split("[a-c]", -1); // ["", "", "", "de"]
    String[] arr2 = s.split("[a-z]", -1); // ["", "", "", "", "", ""]

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

相关文章:

java - 在 Java 中使用传递子类数组作为它们的父类

java - 如何在 Angular 7 中使用字符串添加动态查询参数?

java - 连接到局域网

javascript - 正则表达式文本中包含超过 1 个大写字符的所有单词

javascript - 为什么这个正则表达式不起作用?

java - 为什么在 java 中允许从 long 到 byte 进行窄转换

java - 如何在jsp中设置数据源?

php - 在 Laravel 验证正则表达式规则中验证纬度/经度 - preg_match() : No ending delimiter '/' found

regex - 如何在powershell中的正则表达式中插入变量

java - 使用正则表达式从文本文件中剥离数据