我有两个正则表达式:
[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/