tags:

views:

131

answers:

5

I have a string of the form:

codename123

Is there a regular expression that can be used with Regex.Split() to split the alphabetic part and the numeric part into a two-element string array?

+1  A: 

A little verbose, but

Regex.Split( "codename123", @"(?<=[a-zA-Z])(?=\d)" );

Can you be more specific about your requirements? Maybe a few other input examples.

harpo
There might be backslashes in the codename, but other than that, if it works with "code\name123", it should work for my purposes.
Robert Harvey
This will split the string into `codename`, `1`, `2`, and `3`.
Tim Pietzcker
@Tim, corrected, thanks. I forget that \w matches alphanumeric, not just alpha.
harpo
+3  A: 
splitArray = Regex.Split("codename123", @"(?<=\p{L})(?=\p{N})");

will split between a Unicode letter and a Unicode digit.

Tim Pietzcker
+5  A: 

I know you asked for the Split method, but as an alternative you could use named capturing groups:

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

var alpha = match.Groups["Alpha"].Value;
var num = match.Groups["Numeric"].Value;
Josh
+1 I remember ever seeing one of such implementations for parsing INI files and I honestly thought it's very wonderful.
Alex Essilfie
Using named capturing groups sure beats doing `array[0]`, but that is just me :)
Josh
+3  A: 

Regex is a little heavy handed for this, if your string is always of that form. You could use

"codename123".IndexOfAny(new char[] {'1','2','3','4','5','6','7','8','9','0'})

and two calls to Substring.

Bob
+1  A: 

IMO, it would be a lot easier to find matches, like:

Regex.Matches("codename123", @"[a-zA-Z]+|\d+")
     .Cast<Match>()
     .Select(m => m.Value)
     .ToArray();

rather than to use Regex.Split.

Ani