Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...