[英]Splitting letters and numbers in a string in java
I need to be able to break apart a string into its letters and its numbers. 我需要能够将字符串分成字母和数字。 The strings it will be looking at are something along the lines of 它要看的字符串是类似的东西
"dir1" "path11"
I will also need to temporarily store the 2 values. 我还需要临时存储2个值。 I have found the .split method and it looks like it could be what I'm after but I can't figure out how to use it, should I keep looking into it or is there a better way? 我已经找到了.split方法,它看起来可能是我想要的,但是我不知道如何使用它,我应该继续研究它还是有更好的方法?
Use String.split() as in 使用String.split()作为
String[] strings = "abc111".split("(?=\\d+)(?<=\\D+)");
The split()
function takes a regex around which the string will be split up. split()
函数采用一个正则表达式,该字符串将围绕该正则表达式进行分割。
Here the pattern has two assertions: one which asserts that the characters ahead are digits alone and another one which asserts that the preceding characters are non-digits. 这里的模式有两个断言:一个断言前面的字符只是数字,另一个断言前面的字符是非数字。 So it will split just after the end of non-digits (which is just before the beginning of digits). 因此它将在非数字结尾之后(即在数字开头之前)拆分。
Regex and split can help to do that: 正则表达式和拆分可以帮助实现这一点:
public static void main(String[] args) {
String[] c = "path11".split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
System.out.println(Arrays.toString(c));
}
output= 输出=
[path, 11] [路径,11]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.