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
  • 2,059
  • 1
  • 18
  • 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
  • 44,811
  • 17
  • 103
  • 137
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
  • 14,213
  • 12
  • 75
  • 154
-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,877
  • 28
  • 100
  • 157
Jasmin Solanki
  • 369
  • 7
  • 26
  • 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