C# 正则表达式匹配字母数字和空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/181356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to match alphanumeric and spaces
提问by John Sheehan
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";
采纳答案by Tim
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);
回答by zigdon
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.
您告诉它要做的是用空字符串或任何前导空格替换不是字母数字的所有内容。我认为您的意思是空格可以不替换 - 尝试将 \s 移动到 [] 类中。
回答by JaredPar
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])+"
我想你想要下面的正则表达式 @"([^a-zA-Z0-9\s])+"
回答by Windows programmer
The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.
方括号内的抑扬符表示除后续范围外的所有字符。你想要方括号外的抑扬符。
回答by John Sheehan
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
不知道你可以把 \s 放在括号里
回答by Evolved
This:
这个:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20is ascii hex for 'space' character
\x20是 'space' 字符的 ascii 十六进制
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.
您可以添加更多您希望允许的单个字符。如果你想要例如“?” 在返回字符串中添加\x3f 即可。
回答by vivek
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.
这对我来说很好用。
回答by zamoldar
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