简体   繁体   English

字符串中间的正则表达式验证空间

[英]Regex validation space in the middle of a string

I'm looking for an expression that requires a space in a string, it doesn't have to be dead in the middle just not at the end (or start). 我正在寻找一个需要在字符串中加一个空格的表达式,它不必死在中间而不必在结尾(或开始)。

I've had a look on google and stack-overflow, there are quite a few but I haven't found one that does what I need. 我看过Google和堆栈溢出,有很多,但是我还没有找到能满足我需求的程序。

Here's what I have at the moment 这是我目前的状况

 var re = /^[A-Z]\'?[- a-zA-Z]( [a-zA-Z])*$/igm;

Based on the limited requirements you specified, this will do it. 根据您指定的有限需求,可以做到这一点。 It requires a string to contain ONE space, anywhere but at the start or end. 它需要一个字符串,在开头或结尾之外的任何地方都可以包含一个空格。

/^[^ ]+ [^ ]+$/

Explanation: anchoring to the beginning of the string, allow one or more non-space characters, followed by a single space, followed by, again, one or more non-space characters, to the end of the string. 说明:锚定到字符串的开头,允许一个或多个非空格字符,后跟一个空格,再允许一个或多个非空格字符到字符串的末尾。

[^ ] is a negated character class. [^ ]是否定的字符类。 That is, it says "anything but the characters inside [ and ] . 也就是说,它说:“ []内的字符除外。

Your regex should be: /^[AZ]\\'?[-\\sa-zA-Z](\\s[a-zA-Z])*$/igm; 您的正则表达式应为: /^[AZ]\\'?[-\\sa-zA-Z](\\s[a-zA-Z])*$/igm; . According to my idea, regex doesn't recognize a whitespace that why I replace those with \\s . 根据我的想法,正则表达式无法识别为什么用\\s替换whitespace

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

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