[英]if with regex - string matches either entire string OR entire string + another character?
Sorry if a question like this already has an answer, I wasn't really sure how to word this, so I'll try my best. 抱歉,如果这样的问题已经有了答案,我不确定如何措辞,所以我会尽力而为。
How can I make an if statement match an entire string, OR an entire string with an extra character? 如何使if语句匹配整个字符串,或者匹配带有附加字符的整个字符串?
Let's say the $animals
variable has ,dog,cat,pig,bird,goat,
stored in it. 假设$animals
变量中存储有,dog,cat,pig,bird,goat,
。 I want to see if the user-defined variable $your_pet
is either one of the comma-separated values OR if it is with an "s" at the end. 我想查看用户定义的变量$your_pet
是逗号分隔值之一还是在末尾带有“ s”。
So maybe something that would work like: 因此,也许会像这样工作:
your_pet=bird
if [[ "${your_pet}" == ,*"${animals}"*, || "${your_pet}"s == ,*"${animals}"*, ]]
then
....
However , I need to check if $your_pet
ends in an "s" or not, and accept it if it does or doesn't. 但是 ,我需要检查$your_pet
是否以“ s”结尾,并且接受它是否存在。 (The above code is untested but I am almost certain it would not work). (上面的代码未经测试,但我几乎可以肯定它不起作用)。
Here are all of the allowed values of $your_pet
: 以下是$your_pet
所有允许值:
dog
dogs
cat
cats
pig
pigs
bird
birds
goat
goats
And here are some examples of what would not be allowed: 这里有什么是不允许的一些例子:
my dog
my dogs
dog
hamster
hamsters
I feel like using regex in the if statement would do the trick but I don't know that much about regex to know what to use. 我觉得在if语句中使用regex可以解决问题,但是我对regex不太了解要使用什么。 (if regex is even needed in a situation like this) (如果在这种情况下甚至需要使用正则表达式)
Using bash 3.2.57(1)-release on OS X 10.11.6 El Capitan 在OS X 10.11.6 El Capitan上使用bash 3.2.57(1)-发行版
Thanks 谢谢
You can remove the s
(if present) and then compare if it matches 您可以删除s
(如果存在),然后比较是否匹配
your_pet=bird
if [[ "$animals" =~ ",${your_pet%s}," ]]
then
...
however, take into account other plurals like goose, geese . 但是,要考虑到鹅,鹅等其他复数形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.