简体   繁体   English

如何修改此正则表达式以不允许空格?

[英]How can I modify this regular expression to not allow white spaces?

I have the following regular expression which specifies characters the user is allowed to type: 我有以下正则表达式,用于指定允许用户键入的字符:

@"^[A-Za-z0-9/!\$%\^&\*\(\)\-_\+\[\]\{\}\;\:\'\£\@\#\.\?]*$

I know ' \\s ' is the character class for white space, but how do I add this to the regular expression so it excludes it? 我知道' \\s '是空格字符类,但是如何将其添加到正则表达式中以使其排除呢? I have searched for this on Stack Overflow - the questions provide solutions to exclude white space but not how to use it in an existing regular expression. 我已经在Stack Overflow上进行了搜索-这些问题提供了排除空格的解决方案,但没有提供如何在现有正则表达式中使用空格的解决方案。 If I add it like I have the other characters, it would mean 'allow white space'? 如果我像其他字符一样添加它,那将意味着“允许空白”?

Edit: Not sure why this has been marked down? 编辑:不知道为什么这已被标记下来? Thanks to everyone for their answers 感谢大家的回答

在正则表达式中,方括号中的^表示取反,因此加^\\s表示“不是空白”。

First of all, you don't need all those escapes. 首先,您不需要所有这些转义符。 Second of all, the regex already doesn't allow whitespaces. 第二,正则表达式已经不允许使用空格。

@"^[A-Za-z0-9\[\]/!$%^&*()\-_+{};:'£@#.?]*$"

The [] define a set of characters to allow (followed by * means that characters from the characters set can be zero or more times). []定义了一组允许的字符(后跟*表示该字符集中的字符可以为零或多次)。

^ matches the beginning and $ matches the end, so the fact that /s isn't anywhere there, means white spaces won't be allowed. ^匹配开头,$匹配结尾,因此/ s不在此处的事实意味着不允许使用空格。

In the regular expression, if you don't write "\\s". 在正则表达式中,如果您不写“ \\ s”。 This means your regular expression doesn't allow any blank spaces. 这意味着您的正则表达式不允许有空格。

For example: 1) If I don't want to allow any user to enter blank space in the text box, then the regular expression is written as: 例如:1)如果我不想允许任何用户在文本框中输入空格,那么正则表达式将写为:

Regex alphabet=new Regex(@"^[az]*$"); 正则表达式字母=新的正则表达式(@“ ^ [az] * $”);

2) If the user is allowed to enter any blank space in the text box then the regular expression is written as: 2)如果允许用户在文本框中输入任何空格,则正则表达式将写为:

Regex alphabet=new Regex(@"^[az\\s]*$"); 正则表达式字母=新的正则表达式(@“ ^ [az \\ s] * $”);

3) In regular expression " ^ " means beginning and " $ " means end. 3)在正则表达式中,“ ^”表示开始,“ $”表示结束。

NOTE: ^\\s means negation of "\\s" 注意:^ \\ s表示否定“ \\ s”

Regex regfname = new Regex(@"^[^\\s][a-zA-Z]*$"); 正则表达式regfname =新的正则表达式(@“ ^ [^ \\ s] [a-zA-Z] * $”);

this code will not allow any blank spaces and no empty text box! 此代码将不允许有任何空格和无空文本框!

I hope this will help you to understand the concept of blank spaces in regular expression.. 希望这可以帮助您了解正则表达式中空格的概念。

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

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