Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to split string and number

Tags:

c#

regex

split

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?

like image 379
Robert Harvey Avatar asked Sep 15 '10 17:09

Robert Harvey


People also ask

How split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How do you split a list between letters and digits in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.


3 Answers

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;
like image 143
Josh Avatar answered Oct 01 '22 04:10

Josh


splitArray = Regex.Split("codename123", @"(?<=\p{L})(?=\p{N})");

will split between a Unicode letter and a Unicode digit.

like image 38
Tim Pietzcker Avatar answered Oct 01 '22 03:10

Tim Pietzcker


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.

like image 26
Bob Avatar answered Oct 01 '22 03:10

Bob