Java- Split String which is alphanumeric

前端 未结 3 1698
春和景丽
春和景丽 2021-01-03 05:08

Example input:

RC23
CC23QQ21HD32
BPOASDf91A5HH123

Example output:



        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 05:59

    Try this regex: "((?<=[a-zA-Z])(?=[0-9]))|((?<=[0-9])(?=[a-zA-Z]))"

    Here's a running example: http://ideone.com/c02rmM

    {
        ...
        String someString = "CC23QQ21HD32";
        String regex = "((?<=[a-zA-Z])(?=[0-9]))|((?<=[0-9])(?=[a-zA-Z]))";
        System.out.println(Arrays.asList(someString.split(regex)));
        //outputs [CC, 23, QQ, 21, HD, 32]
        ...
    }
    

    The regex is using lookahead (?=ValueToMatch) and look behinds (?<=ValueToMatch).

    The first half of it (before the | ) is asking: "Is the previous character a letter (?<=[a-zA-Z])? Is the next character a digit (?=[0-9])?" If both are true, it'll match the string to the regex.

    The second half of that regex is doing it the other way around. It asks: "Is the previous character a digit (?<=[0-9])? Is the next character a letter? (?=[a-zA-Z])", and again it'll match if both are true.

    Normally the split() would remove the characters matched by the regex. This remains true even to this regex. However, since the regex is matching a 0-width lookahead, the actual characters you're looking for are not removed.

    Check out Adam Paynter's answer for more on lookaheads and look behinds: how to split string with some separator but without removing that separator in Java?

提交回复
热议问题