Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expressions: how to match a particular word by itself and not when it is in a sentence?

I have a program where the user will type words into an input box and the computer will check the input for key words. I have a slight problem, see below:

  • User input #1: "Perfect"
  • User input #2: "Perfect how are you?"

I created the regex /(\bperfect\b)/ig.

How can I modify my regular expression so that it will only match the word "perfect" by itself and not perfect in user input #2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This regex should work:

/^Perfect$/g

The anchor ^ matches the start of the string and the anchor $ matches the end of the string. More on this here!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading