How to split a string into numeric and alphabetic characters using Regex

I want to split a string like "001A" into "001" and "A"

+3
source share
6 answers
string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"
+4
source
Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;
+4
source

Java, .

    String s = "123XYZ456ABC";
    String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
    System.out.println(Arrays.toString(arr));
    // prints "[123, XYZ, 456, ABC]"

, , \d \d . , .

+2

, 001A, Regex, for-loop.

+1

- , :

StringBuilder sb = new StringBuilder();
Regex regex = new Regex(@"\d*");
MatchCollection matches = regex.Matches(inputString);
for(int i=0; i < matches.count;i++){
    sb.Append(matches[i].value + " ");
}

Then change the regular expression to match the characters and execute the same loop.

0
source

And if you like more 001A002B, you can

    var s = "001A002B";
    var matches = Regex.Matches(s, "[0-9]+|[A-Z]+");
    var numbers_and_alphas = new List<string>();
    foreach (Match match in matches)
    {
        numbers_and_alphas.Add(match.Value);
    }
0
source

Source: https://habr.com/ru/post/1741278/


All Articles