Regex for Matching Literal String Combinations

I'm a noob with regex.

I have to match literally different combinations of strings. Like in the example:

"feed the cat."
"feed the dog."
"feed the bear."

but NOT

"feed the eagle."
"feed the monkey."
"feed the donkey."

I tried something like /^feed the [cat|dog|bear].$/ but it doesn't work. The cheatsheet available on the net explain a lot of complicated things, but not how I can match several strings literally...

Thank you for the help.

2 Answers

You're slightly confusing some syntax. Here's the correct pattern:

^feed the (cat|dog|bear)\.$

You can also use:

^feed the (?:cat|dog|bear)\.$

if you don't need to capture the animal name.

The square brackets are used for character classes, like [a-z] which means "any lowercase letter between a and z, in ASCII".

Also, note that I escaped . with \., because . means "any character except newline" in regex.

You can try following regex,

feed the (cat|dog|bear)

Working Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest