Regular expression to split string and number

前端 未结 8 1909
天涯浪人
天涯浪人 2020-12-03 05:30

I have a string of the form:

codename123

Is there a regular expression that can be used with Regex.Split() to split the alphabetic part and

相关标签:
8条回答
  • 2020-12-03 05:45

    this code is written in java/logic should be same elsewhere

    public String splitStringAndNumber(String string) {
        String pattern = "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)";
    
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(string);
        if (m.find()) {
            return (m.group(1) + " " + m.group(2));
        }
        return "";
    }
    
    0 讨论(0)
  • 2020-12-03 05:49
    splitArray = Regex.Split("codename123", @"(?<=\p{L})(?=\p{N})");
    

    will split between a Unicode letter and a Unicode digit.

    0 讨论(0)
  • 2020-12-03 05:51

    IMO, it would be a lot easier to find matches, like:

    Regex.Matches("codename123", @"[a-zA-Z]+|\d+")
         .Cast<Match>()
         .Select(m => m.Value)
         .ToArray();
    

    rather than to use Regex.Split.

    0 讨论(0)
  • 2020-12-03 05:52

    Regex is a little heavy handed for this, if your string is always of that form. You could use

    "codename123".IndexOfAny(new char[] {'1','2','3','4','5','6','7','8','9','0'})
    

    and two calls to Substring.

    0 讨论(0)
  • 2020-12-03 05:55

    Well, is a one-line only: Regex.Split("codename123", "^([a-z]+)");

    0 讨论(0)
  • 2020-12-03 05:58

    I know you asked for the Split method, but as an alternative you could use named capturing groups:

    var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
    var match = numAlpha.Match("codename123");
    
    var alpha = match.Groups["Alpha"].Value;
    var num = match.Groups["Numeric"].Value;
    
    0 讨论(0)
提交回复
热议问题