'Regex to match alphanumeric and spaces
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";
Solution 1:[1]
This:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20 is ascii hex for 'space' character
you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.
Solution 2:[2]
I got it:
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
Didn't know you could put \s in the brackets
Solution 3:[3]
I suspect ^ doesn't work the way you think it does outside of a character class.
What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.
Solution 4:[4]
The following regex is for space inclusion in textbox.
Regex r = new Regex("^[a-zA-Z\\s]+");
r.IsMatch(textbox1.text);
This works fine for me.
Solution 5:[5]
There appear to be two problems.
- You're using the ^ outside a [] which matches the start of the line
- You're not using a * or + which means you will only match a single character.
I think you want the following regex @"([^a-zA-Z0-9\s])+"
Solution 6:[6]
bottom regex with space, supports all keyboard letters from different culture
string input = "78-selim güzel667.,?";
Regex regex = new Regex(@"[^\w\x20]|[\d]");
var result= regex.Replace(input,"");
//selim güzel
Solution 7:[7]
The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.
Solution 8:[8]
This regex will help you to filter if there is at least one alphanumeric character and zero or more special characters i.e. _ (underscore), \s whitespace, -(hyphen)
string comparer = "string you want to compare";
Regex r = new Regex(@"^([a-zA-Z0-9]+[_\s-]*)+$");
if (!r.IsMatch(comparer))
{
return false;
}
return true;
Create a set using [a-zA-Z0-9]+ for alphanumeric characters, "+" sign (a quantifier) at the end of the set will make sure that there will be at least one alphanumeric character within the comparer.
Create another set [_\s-]* for special characters, "*" quantifier is to validate that there can be special characters within comparer string.
Pack these sets into a capture group ([a-zA-Z0-9]+[_\s-]*)+ to say that the comparer string should occupy these features.
Solution 9:[9]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
Above syntax also accepts space
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
