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
446 views
in Technique[技术] by (71.8m points)

java - Regex split numbers and letter groups without spaces

If I have a string like "11E12C108N" which is a concatenation of letter groups and digit groups, how do I split them without a delimiter space character inbetween?

For example, I want the resulting split to be:

tokens[0] = "11"
tokens[1] = "E"
tokens[2] = "12"
tokens[3] = "C"
tokens[4] = "108"
tokens[5] = "N"

I have this right now.

public static void main(String[] args) {

    String stringToSplit = "11E12C108N";

    Pattern pattern = Pattern.compile("\d+\D+");
    Matcher matcher = pattern.matcher(stringToSplit);

    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

Which gives me:

11E
12C
108N

Can I make the original regex do a complete split in one go? Instead of having to run the regex again on the intermediate tokens?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use the following regex, and get a list of all matches. That will be what you are looking for.

d+|D+

In Java, I think the code would look something like this:

Matcher matcher = Pattern.compile("\d+|\D+").matcher(theString);
while (matcher.find())
{
    // append matcher.group() to your list
}

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

...