java把字符串分割成多分,需要在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).

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?

解决方案

Use lookarounds: str.split("(?<=\\d)(?=\\D)")

String[] parts = "123XYZ".split("(?<=\\d)(?=\\D)");

System.out.println(parts[0] + "-" + parts[1]);

// prints "123-XYZ"

\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).

References

Related questions

Alternate solution using limited split

The following also works:

String[] parts = "123XYZ".split("(?=\\D)", 2);

System.out.println(parts[0] + "-" + parts[1]);

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.

API links

String.split(String regex, int limit)

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值