Raaj TheTalent Brench
Raaj TheTalent Brench

Reputation: 13

Splitting text and integers into array/list

I'm trying to find a way to split a string by its letters and numbers but I've had luck.

An example: I have a string "AAAA000343BBB343"

I am either needing to split it into 2 values "AAAA000343" and "BBB343" or into 4 "AAAA" "000343" "BBB" "343"

Any help would be much appreciated

Thanks

Upvotes: 0

Views: 106

Answers (3)

Jasmin Solanki
Jasmin Solanki

Reputation: 419

Try this:

var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = numAlpha.Match("codename123");

var Character = match.Groups["Alpha"].Value;
var Integer = match.Groups["Numeric"].Value;

Upvotes: -1

fubo
fubo

Reputation: 45947

Here is a RegEx approach to split your string into 4 values

string input = "AAAA000343BBB343";
string[] result = Regex.Matches(input, @"[a-zA-Z]+|\d+")
                       .Cast<Match>()
                       .Select(x => x.Value)
                       .ToArray(); //"AAAA" "000343" "BBB" "343"

Upvotes: 3

Callum Linington
Callum Linington

Reputation: 14417

So you can use regex

For

"AAAA000343" and "BBB343"

var regex = new Regex(@"[a-zA-Z]+\d+");
var result = regex
               .Matches("AAAA000343BBB343")
               .Cast<Match>()
               .Select(x => x.Value);

// result outputs: "AAAA000343" and "BBB343"

For

4 "AAAA" "000343" "BBB" "343"

See @fubo answer

Upvotes: 2

Related Questions