4

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?

2
  • If you only want the last four characters why not substring? Commented May 25, 2011 at 6:44
  • substring i can do but i dont know weather i can have only last 4 characters as numeric.it can be last 5 characters or 3 the below solution is working fine. Commented May 25, 2011 at 7:04

2 Answers 2

5

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");
    }
Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.