-1

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?

Super Jade
  • 2,747
  • 4
  • 22
  • 40
mrpepo877
  • 437
  • 5
  • 18
  • `\w+$` just means that the pattern ends with any number of characters, while `\w` at the end just means that the thing checked by the pattern is to match a single character, but anything else is allowed after that (in theory). – Tim Biegeleisen Jul 29 '18 at 04:15
  • 1
    Try this site for help with regex: https://regexr.com/ It allows you to enter a regex. Then it displays what the regex means. – Super Jade Jul 29 '18 at 04:29

1 Answers1

1

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

Pawan Singh
  • 704
  • 5
  • 10