简体   繁体   English

在Java中的字符串中拆分字母和数字

[英]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.

相关问题 访问字符串中的单个字母/数字中的数字-Java - Accessing single letters in String / digits in numbers - Java 通过拆分正则表达式从Java中的String中提取数字 - Extracting numbers from a String in Java by splitting on a regex Java:将字符串方程拆分为数字和运算符 - Java: Splitting string equation into numbers and operators 检查字符串是否由 3 个大写字母和 4 个数字组成(在 JAVA 中) - Checking if a string is composed of 3 capital letters and 4 numbers (in JAVA) Java字符串:检查连续的字母或数字 - Java String: Checking for consecutive letters or numbers Java方法在字符串中查找大写字母和数字 - Java Method to find uppercase letters and numbers in a String 拆分成对数字的字符串,然后在 java 中拆分每个数字 - Splitting string of pairs of numbers, then splitting each one of them in java 用字母和字母组合将字符串按空格分割成Java中的数组 - Splitting string with letters and letter combinations divided by space into array in Java Java String - 查看字符串是否只包含数字而不包含字母 - Java String - See if a string contains only numbers and not letters 在Java中,如何检查字符串是否同时包含字母和数字,但仅包含字母和数字? - In Java, how do I check if a string consists of both letters and numbers, but only letters and numbers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM