Split String At Every Non-Letter/Non-Number Character

Viewed 585

Imagine a string that contains special characters like $§%%,., numbers and letters.

I want to receive the letter and number junks of an arbitrary string as an array of strings.

A good solution seems to be the use of regex, but I don't know how to express [numbers and letters]

// example
"abc" = {"abc"};
"ab .c" = {"ab", "c"}
"ab123,cd2,  ,,%&$§56" = {"ab123", "cd2", "56"}

// try
string input = "jdahs32455$§&%$§df233§$fd";
string[] output = input.Split(Regex("makejunksfromstring"));
2 Answers

Yes, regex is indeed a good solution for this.

And in fact, to just match all standard words in the input sequence, this is all you need:

(\w+)

Let me quickly explain

\w matches any word character and is equivalent to [a-zA-Z0-9_] - matching a through z or A through Z or 0-9 or _, you might wanna go with [a-zA-Z0-9] instead to avoid that underscore.

Wrapping an expression in () means that you want to capture that part as a group.

The + means that you want sequences of 1 or more of the preceding characters.

Refer to a regular expression cheat sheet to see all the possibilities, such as https://cheatography.com/davechild/cheat-sheets/regular-expressions/

Or any that you find online.

Also there are tools available to quickly test out your regular expressions, such as https://regex101.com/ (quite well visualised matching) or http://regexstorm.net/tester specifically for .NET

To extract chunks of 1 or more letters/digits you may use

[A-Za-z0-9]+   # ASCII only letters/digits
[\p{L}0-9]+    # Any Unicode letters and ASCII only digits 
[\p{L}\p{N}]+  # Any Unicode letters/digits 

See a regex demo.

C# usage:

string[] output = Regex.Matches(input, @"[\p{L}\p{N}]+").Cast<Match>().Select(x => x.Value).ToArray();
Related