JaX
JaX

Reputation: 187

String Manipulation in Java: split string after numbers

My string have this form XxYxZx

X , Y and Z are characters and the x are numbers which can vary from 0-999.

I want to split this string in this form. How can this be done?

  1. Xx
  2. Yx
  3. Zx

Example:

 Input:  "A155B45C77D89" 
 Output: "A155", "B45", "C77", "D89"

Upvotes: 0

Views: 259

Answers (2)

aioobe
aioobe

Reputation: 420951

String myString="A155B45C77D89";
String[] parts = myString.split("(?<=\\d)(?=\\p{Alpha})");
System.out.println(Arrays.toString(parts));

Output:

[A155, B45, C77, D89]

Explanation:

String.split works with regular expressions. The regular expression (?<=\d)(?=\p{Alpha}) says "match all substrings preceeded by a digit, succeeeded by a alphabetic character.

In a string such as "A155B45C77D89", this expression is matched by the empty substrings

A155 B45 C77 D89
    ^   ^   ^
  here  |   |
       here |
            |
        and here

Upvotes: 7

stacker
stacker

Reputation: 68942

public static void main(String[] args) {
        Pattern p = Pattern.compile( "([A-Z])([0-9]+)" );
        Matcher m = p.matcher( "X01Y123Z99" );
        while ( m.find() ) {
            System.out.println( m.group( 1 ) + " " + m.group( 2 ) );
        }
    }

prints

X 01
Y 123
Z 99

Upvotes: 1

Related Questions