regex for matching literal string combinations

那年仲夏 提交于 2021-02-16 17:00:42

问题


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.


回答1:


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.




回答2:


You can try following regex,

feed the (cat|dog|bear)

Working Demo



来源:https://stackoverflow.com/questions/29835568/regex-for-matching-literal-string-combinations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!