I was doing a hackerrank here and I did the following code:
/^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w/
But the answer was
/^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w+$/
and I don't understand the last part of that regex. What is it?
I was doing a hackerrank here and I did the following code:
/^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w/
But the answer was
/^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w+$/
and I don't understand the last part of that regex. What is it?
Here, \w
will select An alphanumeric character (“word character”), and When you put a plus sign (+) after something in a regular expression, it indicates that the element may be repeated more than once.
Thus, /\w+/ matches one or more alphanumeric characters.
And $ here means End of string.
Example 1 --- /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w$/.test('Mr.J'); // true
Example 2 --- /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w$/.test('Mr.Joseph'); // false
Example 3 --- /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)\w+$/.test('Mr.Joseph'); // true