C#正则表达式-接受字符串中的空格 [英] C# Regex - Accept spaces in a string
问题描述
我有一个需要对某些字段进行验证的应用程序.其中之一是姓氏,可以由2个单词组成.在我的正则表达式中,我必须接受这些空格,所以我尝试了很多事情,但没有找到任何解决方案.
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. In my regex, I have to accept these spaces so I tried a lot of things but I did'nt find any solution.
这是我的正则表达式:
@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$"
\ s
通常用于空格,但是它不起作用,并且出现了此错误消息:
The \s
are normally for the spaces but it does not work and I got this error message :
parsing "^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ-\s]+$" - Cannot include class \s in character range.
有个好主意吗?
推荐答案
-
表示字符范围,就像您使用 AZ
来描述A和Z .您的正则表达式使用ñ-\ s
,引擎尝试将其解释为ñ和\ s 之间的任何字符-然后注意到,该 \ s
并没有太多意义,因为 \ s
本身只是任何空白字符的缩写.
-
denotes a character range, just as you use A-Z
to describe any character between A and 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.
那是错误的出处.
要摆脱这一点,如果要包含-
文字字符:
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-]+$"
通过这种方式,引擎知道 \ s-
不是字符范围,而是两个字符 \ s
和-
分开.
This way, the engine knows that \s-
is not a character range, but the two characters \s
and -
seperately.
另一种方法是转义-
字符:
The other way is to escape the -
character:
@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêç\-\s]+$"
因此,现在引擎将ñ\-\ s
解释为不是字符范围,而是解释为任何字符ñ
,-
或 \ s
.就个人而言,尽管我总是尽量避免转义,因为恕我直言,它会变得杂乱无章,并不必要地延长表达式的长度.
So now the engine interprets ñ\-\s
not as a character range, but as any of the characters ñ
, -
or \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.
这篇关于C#正则表达式-接受字符串中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!