需要帮助使用正则表达式在java中拆分字符串

时间:2021-06-04 02:02:21

I have a string like "portal100common2055".

我有一个像“portal100common2055”的字符串。

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

我想把它分成两部分,第二部分应该只包含数字。

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

“portal200511sbet104”将成为“portal200511sbet”,“104”

Can you please help me to achieve this?

你能帮助我实现这个目标吗?

2 个解决方案

#1


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

#2


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)表示在当前点,确保前面的字符以非数字结尾(非数字表示为\ 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)
  • (?= \\ d + $)表示当前点,确保在输入的末尾只找到数字(数字表示为\ d)

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

这只会在想要分割输入的所需点处为真

#1


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

#2


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)表示在当前点,确保前面的字符以非数字结尾(非数字表示为\ 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)
  • (?= \\ d + $)表示当前点,确保在输入的末尾只找到数字(数字表示为\ d)

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

这只会在想要分割输入的所需点处为真