将一个String与一个表达式中的多个值进行比较 [英] Compare one String with multiple values in one expression

查看:76
本文介绍了将一个String与一个表达式中的多个值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String变量, str 包含可能的值, val1 val2 val3

I have one String variable, str with possible values, val1, val2 and val3.

我想比较(相同的情况下)<$ c $使用if语句c> str 到所有这些值,例如:

I want to compare (with equal case) str to all of these values using an if statement, for example:

if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3.equalsIgnoreCase(str))
{
      //remaining code
}

有没有办法避免使用多个OR(||)运算符并比较一个表达式中的值?例如,像这样:

Is there a way to avoid using multiple OR (||) operators and compare values in one expression? For example, like this:

 if(("val1" OR "val2" OR "val3").equalsIgnoreCase(str)   //this is only an idea.


推荐答案

我找到了更好的解决方案。这可以通过RegEx实现:

I found the better solution. This can be achieved through RegEx:

if (str.matches("val1|val2|val3")) {
     // remaining code
}

对于不区分大小写的匹配:

For case insensitive matching:

if (str.matches("(?i)val1|val2|val3")) {
     // remaining code
}

这篇关于将一个String与一个表达式中的多个值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆