Reputation: 61
My job is to create a regular expression that matches any of the variations on the name: vic, Victor, Victoria, victor, Victoria, VICKY, VICTOR. VICTORIA, Vic, VIC
and so I wrote this
(Vic[a-z])|(vic[a-z])|(VIC[A-Z]*)
I have a problem though. For example if I typed "Hello aVictoria", it would match the string "Victoria"...How do I make it to match such that the first character has to be V or v?
Upvotes: 1
Views: 116
Reputation: 2671
Try this
/\bvic[a-zA-Z]{0,}/ig
for Explanation
Sample Example
'vic, Victor, Victoria, victor, Victoria, VICKY, VICTOR. VICTORIA, Vic, VIC, Hello aVictoriaX'.match(/\bvic[a-zA-Z]{0,}/ig)
//output
["vic", "Victor", "Victoria", "victor", "Victoria", "VICKY", "VICTOR", "VICTORIA", "Vic", "VIC"]
//Hello aVictoriaX isn't matched
Upvotes: 0
Reputation: 174706
You failed to add *,
(Vic[a-z]*)|(vic[a-z]*)|(VIC[A-Z]*)
In the below regex, you failed to add +
or *
on the first two regexes,
(Vic[a-z])|(vic[a-z])|(VIC[A-Z]*)
(Vic[a-z])
- It matches any single alphabetical character after Vic but it wont match more than one character after that word Vic
.
Upvotes: 1
Reputation: 12772
^
character to indicate start of string, like
^(Vic[a-z])|(vic[a-z])|(VIC[A-Z]*)
Upvotes: 0
Reputation: 198324
If you need start of the word, you can use \b
(word boundary 0-width matcher). If you need start of the line, you should use ^
(start of the line 0-width matcher). Regexp engines that also have multi-line capabilities will also define \A
(start of the string 0-width matcher). Depending on what you want, stick one of those in front of your regexp, like this:
^((Vic[a-z])|(vic[a-z])|(VIC[A-Z]*))
(You also need extra parentheses, because otherwise you would match "Victor" only at start, but "victor" and "VICTOR" anywhere at all.)
That said, this won't match "vic", since you are requiring another [a-z]
after it. This would be the correct regexp:
^((Vic[a-z]*)|(vic[a-z]*)|(VIC[A-Z]*))
This will match "Victor", but not "aVictor". If you write \b
instead of ^
, you will additionally match "I am not a Victor" (while still disallowing "aVictor").
Upvotes: 0