Raja
Raja

Reputation: 77

Need help to split string in java using regex

I have a string like "portal100common2055".

I would like to split this into two parts, where the second part should only contain numbers.

"portal200511sbet104" would become "portal200511sbet", "104"

Can you please help me to achieve this?

Upvotes: 4

Views: 316

Answers (2)

Bohemian
Bohemian

Reputation: 425358

String[] parts = input.split("(?<=\\D)(?=\\d+$)");
if (parts.length < 2) throw new IllegalArgumentException("Input does not end with numbers: " + input);
String head = parts[0];
String numericTail = parts[1];

This more elegant solution uses the look behind and look ahead features of regex.

Explanation:

  • (?<=\\D) means at the current point, ensure the preceding characters ends with a non-digit (a non-digit is expressed as \D)
  • (?=\\d+$) means t the current point, ensure that only digits are found to the end of the input (a digit is expressed as \d)

This will only the true at the desired point you want to divide the input

Upvotes: 3

Simon G.
Simon G.

Reputation: 6717

Like this:

    Matcher m = Pattern.compile("^(.*?)(\\d+)$").matcher(args[0]);
    if( m.find() ) {
        String prefix = m.group(1);
        String digits = m.group(2);
        System.out.println("Prefix is \""+prefix+"\"");
        System.out.println("Trailing digits are \""+digits+"\"");
    } else {
        System.out.println("Does not match");
    }

Upvotes: 5

Related Questions