Skip to content
Advertisement

Regular expression matching strings where it contains a specific word that has a period

I am trying to write a regular expression that matches string that contain a certain word with a period for example (apple. or grape.). I got it to work without the period but not quite sure how to get it to work when there is a period in the word.

What I tried:

JavaScript

Sample strings that should work:

JavaScript

Sample strings that should not work:

JavaScript

Advertisement

Answer

You could write the pattern as:

JavaScript

Explanation

  • b A word boundary to prevent a partial word match on the left
  • (Apple|Grape) Capture either Apple or Grape
  • . Match a dot
  • (?!S) Assert a whitespace boundary to the right

Regex demo

In Java with the double escaped backslashes:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement