Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for matching literal string combinations

Tags:

regex

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.

like image 679
user3154898 Avatar asked Apr 23 '15 22:04

user3154898


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


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.

like image 149
Lucas Trzesniewski Avatar answered Oct 11 '22 20:10

Lucas Trzesniewski


You can try following regex,

feed the (cat|dog|bear)

Working Demo

like image 38
apgp88 Avatar answered Oct 11 '22 21:10

apgp88