开发者

Need help to split string in java using regex

开发者 https://www.devze.com 2023-03-08 01:04 出处:网络
I have a string like \"portal100common2055\". I would like to split this into two parts, where the second part should only contain numbers.

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"开发者_JAVA技巧

Can you please help me to achieve this?


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");
    }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号