Java (Regex?) split string between number/letter combination

前端 未结 5 1948
甜味超标
甜味超标 2021-01-05 08:44

I\'ve been looking through pages and pages of Google results but haven\'t come across anything that could help me.

What I\'m trying to do is split a string like

相关标签:
5条回答
  • 2021-01-05 08:59

    Try this

    String s = "Bananas22Apples496Pears3";
    
    String[] res = s.replaceAll("(?<=\\p{L})(?=\\d)", ":").split("(?<=\\d)(?=\\p{L})");
        for (String t : res) {
            System.out.println(t);
        }
    

    The first step would be to replace the empty string with a ":", when on the left is a letter with the lookbehind assertion (?<=\\p{L}) and on the right is a digit, with the lookahead assertion (?=\\d).

    Then split the result, when on the left is a digit and on the right is a letter.

    \\p{L} is a Unicode property that matches every letter in every language.

    0 讨论(0)
  • 2021-01-05 09:14
    String myText = "Bananas22Apples496Pears3";
    System.out.println(myText.replaceAll("([A-Za-z]+)([0-9]+)", "$1:$2,"));
    
    0 讨论(0)
  • 2021-01-05 09:20

    This should do what you want:

    import java.util.regex.*;
    
    String d = "Bananas22Apples496Pears3"
    
    Pattern p = Pattern.compile("[A-Za-z]+|[0-9]+");
    
    Matcher m = p.matcher(d);
    
    while (m.find()) {
          System.out.println(m.group());
    }
    
    // Bananas
    // 22
    // Apples
    // 496
    // Pears
    // 3
    
    0 讨论(0)
  • 2021-01-05 09:24

    Replace \d+ by :$0 and then split at (?=[a-zA-Z]+:\d+).

    0 讨论(0)
  • 2021-01-05 09:26

    You need to Replace and then split the string.You can't do it with the split alone

    1> Replace All the string with the following regex

    (\\w+?)(\\d+)
    

    and replace it with

    $1:$2
    

    2> Now Split it with this regex

    (?<=\\d)(?=[a-zA-Z])
    
    0 讨论(0)
提交回复
热议问题