Split string into multiple alpha and numeric segments

Viewed 579

I have a string like "ABCD232ERE44RR". How can I split it into separate segments by letters/numbers. I need: Segment1: ABCD Segment2: 232 Segment3: ERE Segment4: 44

There could be any number of segments. I am thinking go Regex but don't understand how to write it properly

4 Answers

You can do it like this;

using System;
using System.Collections.Generic;   
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        var substrings = Regex.Split("ABCD232ERE44RR", @"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
        Console.WriteLine(string.Join(",",substrings));
    }
}

Output : ABCD,232,ERE,44,RR

I suggest thinking of this as finding matches to a target pattern rather than splitting into the parts you want. Splitting gives significance to the delimiters whereas matching gives significance to the tokens.

You can use Regex.Matches:

Searches the specified input string for all occurrences of a specified regular expression.

var matches = Regex.Matches("ABCD232ERE44RR", "[A-Z]+|[0-9]+");

foreach (Match match in matches) {
     Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
}

Try something like:

((A-Z)+(\d)*)+

If you decide not to use regex, you can always go the manual route.

const string str = "ABCD232ERE44RR1SGGSG3333GSDGSDG";

var result = new List<StringBuilder> 
{
    new StringBuilder()
};

char last = str[0];

result.Last().Append(last);

bool isLastNum = Char.IsNumber(last);

for (int i = 1; i < str.Length; i++)
{
    char ch = str[i];

    if (!((Char.IsDigit(ch) && isLastNum) || (Char.IsLetter(ch) && !isLastNum)))
    {
        result.Add(new StringBuilder());
    }

    result.Last().Append(ch);
    last = ch;
    isLastNum = Char.IsDigit(ch);
}
Related