Separating alphabets and digits from Alphanumeric string– C#
We got a requirement to separate alphabets and digits from alphanumeric string as groups.
Let’s say my alphanumeric string is “Hel00Wor11DD” and I need to get
- Alphabet group as “Hel,Wor,DD”
- Digit group as “00,11”.
Below is the C# code which use Regular expressions and achieve the same
var digitGroup = newList<string>();
var alphabetGroup = newList<string>();
Match regexMatch = null;
string myString = “Hel00Wor11DD”;
while (myString.Length > 0){
if ((regexMatch = Regex.Match(myString, “\\d”)).Success){
// If myString is not starting with digit
if (regexMatch.Index > 0) {
alphabetGroup.Add(myString.Substring(0, regexMatch.Index));
}
// If myString is starting with digits but has subsequent alphabets
elseif ((regexMatch = Regex.Match(myString, “\\D”)).Success) {
digitGroup.Add(myString.Substring(0, regexMatch.Index));
}
// If myString only has digits, no more alphabets
else{
digitGroup.Add(myString.Substring(0));
// No more alphabets
break;
}
myString = myString.Substring(regexMatch.Index);
}
// There are no digits in myString
else{
alphabetGroup.Add(myString);
// No more digits
break;
}
}
When you run above code, you would get Alphabets & Digits separated as Lists.
🙂