Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into multiple alpha and numeric segments

Tags:

c#

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

like image 699
anjulis Avatar asked Aug 27 '26 22:08

anjulis


2 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
like image 154
lucky Avatar answered Aug 29 '26 11:08

lucky


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);
}
like image 41
allonhadaya Avatar answered Aug 29 '26 11:08

allonhadaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!