简体   繁体   English

C#正则表达式-接受字符串中的空格

[英]C# Regex - Accept spaces in a string

I have an application which needs some verifications for some fields. 我有一个需要对某些字段进行验证的应用程序。 One of them is for a last name which can be composed of 2 words. 其中之一是姓氏,可以由2个单词组成。 In my regex, I have to accept these spaces so I tried a lot of things but I did'nt find any solution. 在我的正则表达式中,我必须接受这些空格,所以我尝试了很多事情,但没有找到任何解决方案。

Here is my regex : 这是我的正则表达式:

@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$"

The \\s are normally for the spaces but it does not work and I got this error message : \\s通常用于空格,但是它不起作用,并且我收到此错误消息:

parsing "^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$" - Cannot include class \s in character range.

ANy idea guys? 大家有想法吗?

- denotes a character range, just as you use AZ to describe any character between A and Z . -表示字符范围,就像使用AZ来描述A和Z之间的任何字符一样 Your regex uses ñ-\\s which the engine tries to interpret as any character between ñ and \\s -- and then notices, that \\s doesn't make a whole lot of sense there, because \\s itself is only an abbreviation for any whitespace character. 您的正则表达式使用ñ-\\s ,引擎会尝试将其解释为ñ和\\ s之间的任何字符 -然后注意, \\s在那里并没有多大意义,因为\\s本身只是的缩写 。任何空白字符。

That's where the error comes from. 这就是错误的来源。

To get rid of this, you should always put - at the end of your character class, if you want to include the - literal character: 要摆脱这一点,如果要包含-文字字符,则应始终字符类末尾放置-

@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ\s-]+$"

This way, the engine knows that \\s- is not a character range, but the two characters \\s and - seperately. 这样,引擎就知道\\s-不是字符范围,而是两个字符\\s-分开。

The other way is to escape the - character: 另一种方法是转义-字符:

@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêç\-\s]+$"

So now the engine interprets ñ\\-\\s not as a character range, but as any of the characters ñ , - or \\s . 因此,现在引擎将ñ\\-\\s解释为不是字符范围,而是任何ñ-\\s字符 Personally, though I always try to avoid escaping as often as possible, because IMHO it clutters up and needlessly stretches the expression in length. 就个人而言,尽管我总是尽量避免转义,因为恕我直言,它会变得混乱并且不必要地延长表达式的长度。

You need to escape the last - character - ñ-\\s is parsed like the range az : 您需要转义最后一个-字符ñ-\\s的解析范围为az

@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ\-\s]+$"

See also on Regex Storm: [a-\\s] , [a\\-\\s] 另请参见Regex Storm: [a-\\s][a\\-\\s]

[RegularExpression(@"^[a-zA-Z\\s]+$", ErrorMessage = "Only alphabetic characters and spaces are allowed.")] [RegularExpression(@“ ^ [a-zA-Z \\ s] + $”,ErrorMessage =“仅允许使用字母和空格。”]]

This works 这有效

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

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