需要在Java中将字符串分成两部分 [英] Need to split a string into two parts in java
问题描述
我有一个字符串,其中包含一个连续的数字块,然后是一个连续的字符块.我需要将它们分为两部分(一个整数部分和一个字符串).
I have a string which contains a contiguous chunk of digits and then a contiguous chunk of characters. I need to split them into two parts (one integer part, and one string).
我尝试使用String.split("\\D", 1)
,但它正在占用第一个字符.
我检查了所有String API,但没有找到合适的方法.
I tried using String.split("\\D", 1)
, but it is eating up first character.
I checked all the String API and didn't find a suitable method.
有什么方法可以做这件事吗?
Is there any method for doing this thing?
推荐答案
使用环顾方法:str.split("(?<=\\d)(?=\\D)")
String[] parts = "123XYZ".split("(?<=\\d)(?=\\D)");
System.out.println(parts[0] + "-" + parts[1]);
// prints "123-XYZ"
\d
是数字的字符类; \D
是它的否定.因此,此零位匹配断言匹配前一个字符为数字(?<=\d)
且后一个字符为非数字(?=\D)
的位置.
\d
is the character class for digits; \D
is its negation. So this zero-matching assertion matches the position where the preceding character is a digit (?<=\d)
, and the following character is a non-digit (?=\D)
.
- Java split is eating my characters.
- Is there a way to split strings with String.split() and include the delimiters?
以下内容也适用:
String[] parts = "123XYZ".split("(?=\\D)", 2);
System.out.println(parts[0] + "-" + parts[1]);
这会在我们看到一个数字之前分裂.这与您的原始解决方案更加接近,除了它实际上与非数字字符不匹配之外,不会吃掉"它.另外,它使用的是2
中的limit
,这确实是您想要的.
This splits just before we see a non-digit. This is much closer to your original solution, except that since it doesn't actually match the non-digit character, it doesn't "eat it up". Also, it uses limit
of 2
, which is really what you want here.
String.split(String regex, int limit)
- If the limit
n
is greater than zero then the pattern will be applied at mostn - 1
times, the array's length will be no greater thann
, and the array's last entry will contain all input beyond the last matched delimiter.
这篇关于需要在Java中将字符串分成两部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- If the limit