Reputation: 7724
In JavaScript I am using the regular expression /^([a-z]){3}^(foo)/i
to try and match a specific word and the word's length. The regex should also be case insensitive. So I added an i
modifier on the end.
What I think this says it should do is
^ : 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
However when I tested this with the following strings fOo
, foo
, Foo
, FoO
it didn't return any matches.
I would appreciate it if someone could explain what I am doing wrong and help me fix it.
Edit for Sukima
Example strings which should work:
fOo
FoO
foo
FOO
Example string which shouldn't work
f o o
adfsFoO
fooFoe
FfOoF
:fdFoo:
The aim of the regex is to check that the string matches the word foo
exactly and is length of 3
exactly.
Upvotes: 2
Views: 659
Reputation: 6469
Hence foo
actually is a subset of your prior regex, the following should do the trick:
/^\w{3})/i
or one of the following if numbers are not allowed:
/^[a-z]{3}/i
/^[A-a]{3}/
This regex matches every word of exactly three characters at the beginning of the string (or line if you specify the /m modifier) regardless if its upper- or lowercase.
if you need to match the word foo precisely regardless of its case just go for:
/^foo$/i
Example matches: fOo
, fOo
, foo
, Foo
, FoO
... more available on regex101
Upvotes: 5
Reputation: 10064
You have two issues in that regexp. First the ^
means start of line which is meaningless unless it is the first character in the regexp pattern.
Second the pattern [a-z]{3}
will match foo
anyway so the second pattern is just noise.
Think what you want is simply ^[a-z]{3}
which will match foo
in foo
and foobar
.
As an aside if you want to match more than one pattern at start (or end) of line then you have to separate the patterns with a pipe |
.
^foo|^bar
will match foo
and bar
, but not bazbar
or bazfoo
.
Upvotes: 0