简体   繁体   English

正则表达式匹配字母数字和空格

[英]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";

just a FYI 只是一个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);

This: 这个:

string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);

\\x20 is 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 . 在返回字符串add \\ x3f中没问题

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放在括号中

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移动到[]类中。

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. 这对我来说很好。

There appear to be two problems. 似乎有两个问题。

  1. You're using the ^ outside a [] which matches the start of the line 你在[]之外使用^匹配行的开头
  2. 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])+”

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

The circumflex inside the square brackets means all characters except the subsequent range. 方括号内的旋律表示除后续范围外的所有字符。 You want a circumflex outside of square brackets. 你想要方括号外的旋风。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM