Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match alphanumeric and spaces

Tags:

c#

regex

What am I doing wrong here?

string q = "john s!"; string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty); // clean == "johns". I want "john s"; 
like image 261
John Sheehan Avatar asked Oct 08 '08 04:10

John Sheehan


People also ask

Is space allowed in alphanumeric?

Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.

How do you write alphanumeric in regex?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

How do you check for space in regex?

The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].

Are spaces allowed in regex?

Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.


1 Answers

just a FYI

string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty); 

would actually be better like

string clean = Regex.Replace(q, @"[^\w\s]", string.Empty); 
like image 81
Tim Avatar answered Sep 24 '22 05:09

Tim