在JavaScript中,我使用正则表达式/^([a-z]){3}^(foo)/i来尝试匹配特定单词和单词的长度.正则表达式也应该不区分大小写.所以我最后添加了一个i修饰符.
我认为这应该做的是
^ : Start at beginning of string
([a-z]){3} : Match [a-z] exactly three times
^ : Go back to start of string
(foo) : Match the word foo exactly
Run Code Online (Sandbox Code Playgroud)
然而,当我测试了与下列字符串fOo,foo,Foo,FoO它并没有找到任何匹配.
如果有人能解释我做错了什么并帮助我解决它,我将不胜感激.
为Sukima编辑
应该工作的示例字符串:
fOo
FoO
foo
FOO
Run Code Online (Sandbox Code Playgroud)
示例字符串不应该工作
f o o
adfsFoO
fooFoe
FfOoF
:fdFoo:
Run Code Online (Sandbox Code Playgroud)
正则表达式的目的是检查字符串是否与单词foo完全匹配,并且是3精确的长度.
因此foo实际上是你之前的正则表达式的一个子集,以下应该做的诀窍:
/^\w{3})/i
Run Code Online (Sandbox Code Playgroud)
如果不允许,则为以下之一:
/^[a-z]{3}/i
/^[A-a]{3}/
Run Code Online (Sandbox Code Playgroud)
此正则表达式匹配字符串开头的正好三个字符的每个单词(如果指定/ m修饰符,则为行),无论其大写还是小写.
如果您需要精确匹配单词foo,无论其情况如何,只需:
/^foo$/i
Run Code Online (Sandbox Code Playgroud)
示例匹配:fOo,fOo,foo,Foo,FoO...更可在regex101