正则表达式,允许在字符或单词后留空格 [英] Regular expression to allow single space after character or word
问题描述
我正在寻找一个正则表达式,该表达式允许用户在一个单词或字符之后的第二个单词或字符之前仅输入字母和单个空格.
I am looking out for a regular expression that allows user to enter just alphabets and single space after one word or character before second word or character.
这是我到目前为止所做的.
this is what I have done so far.
^[\w ]+$
但只检查单词.
我需要上述内容来验证姓名.
I require the above to validate name.
我希望用户避免键入诸如}{[]""<>?/\
之类的字符...
I want user to avoid typing characters like }{[]""<>?/\
and so on...
我的jsfiddle不允许我这样做
my jsfiddle it does not allow me thing
推荐答案
您的正则表达式^[\w ]+$
允许单词字符\w
或空格的任意组合中的一个或多个,连续包含多个空格,或者除空格之外.您也不需要\w
,因为它与单词"字符匹配,而出于某种原因,单词"被定义为包括数字和下划线.
Your regex, ^[\w ]+$
, allows one or more of any combination of word characters \w
or spaces, included several spaces in a row or nothing but spaces. You don't want \w
either, because it matches "word" characters where for some reason "word" has been defined as including digits and underscores.
请尝试以下操作:
^[A-Za-z']+( [A-Za-z']+)*$
这将匹配:
^ beginning of string
[A-Za-z']+ one or more letters or apostrophe
( [A-Za-z']+)* zero or more instances of (a single space followed by
by one or more letters or apostrophe)
$ end of string
您没有提到撇号,但我添加了撇号以允许使用O'Conner之类的名称.
You didn't mention apostrophes, but I added it in to allow for names like O'Conner.
但是请注意,这不包括很多非英语名称.假设您要在此处验证人们的姓名,我认为最好还是让用户输入他们想要输入的内容.
Note though that this excludes quite a few non-English names. Assuming you're validating people's names here I think you're better off just letting the user enter what they want to enter.
这篇关于正则表达式,允许在字符或单词后留空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!