0

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

Chathuranga Tennakoon
  • 1,881
  • 1
  • 16
  • 20

3 Answers3

3

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"
fubo
  • 42,334
  • 17
  • 98
  • 130
2

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

Callum Linington
  • 13,662
  • 12
  • 67
  • 145
-1

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;
Tassisto
  • 9,235
  • 27
  • 93
  • 145
Jasmin Solanki
  • 319
  • 6
  • 19
  • This will only grab the first instance of letters and numbers, not both. You should try it with the provided data, instead of `codename123`. Good use of named captures, though. – Bobson Jul 20 '16 at 10:37