简体   繁体   English

JavaScript正则表达式-仅接受两个不带特殊字符的单词

[英]JavaScript Regular Expression - Accept only two words with no special characters

I am trying this below pattern in http://regex101.com/#javascript 我正在http://regex101.com/#javascript中尝试以下模式

Pattern: [a-zA-Z]+\\s{1}[a-zA-Z]+ 格式: [a-zA-Z]+\\s{1}[a-zA-Z]+

String: 'Testing Only two characters' 字符串: 'Testing Only two characters'

http://regex101.com/r/gT0uX9 highlights only first two words of the string but when I try it in a fiddle, it says true. http://regex101.com/r/gT0uX9仅突出显示字符串的前两个单词,但是当我在小提琴中尝试时,它表示是正确的。 What is the problem? 问题是什么? Am I doing something wrong? 难道我做错了什么?

Fiddle 小提琴

Because .test() checks whether the regex matches or not. 因为.test()检查正则表达式是否匹配。 In your case it is matching correctly and hence true 在您的情况下,它正确匹配,因此是正确的

What the doc says: 医生说什么:

Use test() whenever you want to know whether a pattern is found in a string (similar to the String.search method); 每当您想知道是否在字符串中找到模式时都使用test()(类似于String.search方法); for more information (but slower execution) use the exec method (similar to the String.match method). 有关更多信息(但执行速度较慢),请使用exec方法(类似于String.match方法)。 As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match. 与exec(或与exec结合使用)一样,在同一全局正则表达式实例上多次调用的test将前进到先前的匹配。

( emphasis mine ) You can use anchors ^ and $ if you want only two words. 我的重点是 )如果只需要两个单词,可以使用锚点^$

^[a-zA-Z]+\s{1}[a-zA-Z]+$

It returns true because your string contains a string of two words. 它返回true因为您的字符串包含两个单词的字符串。 If you want to check whether the string is a string of two words, use the anchors ^ and $ for start-of-string and end-of-string: 如果要检查字符串是否两个单词的字符串,请使用锚点^$表示字符串的开头和结尾:

^[a-zA-Z]+\s{1}[a-zA-Z]+$

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

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