Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split alphanumeric string to array containing the alphabet and numeric characters separately

I'm looking to find a way to split an alphanumeric string like

"Foo123Bar"

into an array that contains it like so

array[0] = "Foo"
array[1] = "123"
array[2] = "Bar"

I'm not sure what the best way to achieve this is, especially because the strings I'm comparing follow no specific pattern as far as which is first, alphabet or numbers, or how many times they each appear. For example it could look like any of the following:

"Foo123Bar"
"123Bar"
"Foobar123"
"Foo123Bar2"

I'm trying to find out if there is a more efficient way of doing this other than splitting the string character by character and checking to see if it's numeric.

like image 463
Nvx Avatar asked Sep 24 '13 21:09

Nvx


1 Answers

string input = "Foo123Bar";
var array = Regex.Matches(input, @"\D+|\d+")
                 .Cast<Match>()
                 .Select(m => m.Value)
                 .ToArray();
like image 117
I4V Avatar answered Sep 28 '22 10:09

I4V