我正在使用一些Java代码,它由一个比较字符串的switch语句组成。在学习之前大约有5个案例需要添加更多内容。
实际上我需要添加64个案例(4组,16个类似拼写的值),并且由于字符串的性质,希望使用正则表达式不需要这么多语句。例如,第一组可能值是“Section ## Stuff”,第二组是“Section ## Stuff XYZ”,依此类推;其中##是1到16之间的任何数字。
为了澄清,我没有为每个字符串添加一个大小写,而是想重新输出类型,然后调用相应的函数等。
虽然这一切都正常,但我担心其他开发人员很难理解正在发生的事情,因为我基本上结合了正则表达式if语句和switch语句。我也不能忍受非常大的switch语句列表。
什么是更好的选择(可读性与口才等),是否有可能以某种方式在我的switch语句中使用正则表达式?此外,我认为不会有任何重大的性能损失,但如果有,那就很高兴知道。 :)
下面的代码是一个例子,因为我无法提供真实的代码。
我想做什么:
if (str.matches("Section ([1-9]|1[0-6]) Stuff") {
//do something with the number provided in string
} else if (str.matches("Section ([1-9]|1[0-6]) Stuff 2") {
//do something else with the number provided in the string
} else {
switch (str) {
case PARAM_VALUE_1:
doSomething1();
break;
case PARAM_VALUE_2:
doSomething2();
break;
...
...
default:
break;
}
}
或 -
switch (str) {
case PARAM_VALUE_1:
doSomething1();
break;
case PARAM_VALUE_2:
doSomething2();
break;
...
...
case "Section 1 Stuff":
//do something for section 1
break;
case "Section 2 Stuff":
//do something for section 2
break;
...
... (64 cases later)
default:
break;
}
}
注意:我无法重新设计字符串的来源;它来自另一个子系统,它就是它。
感谢您的帮助!
答案 0 :(得分:1)
对于这种情况,您可以考虑使用Java枚举,利用它们的重写功能。
enum MyEnum {
SectionOne("Section ([1-9]|1[0-6]) Stuff") {
@Override
public void doSomething() {
// implementation for section one when regex matches
}
}, SectionTwo("Section ([1-9]|1[0-6]) Stuff 2") {
@Override
public void doSomething() {
// implementation for section two when regex matches
}
}, Param1("ParamValue1") {
@Override
public void doSomething() {
// implementation for param 1
}
}, Param2("ParamValue2") {
@Override
public void doSomething() {
// implementation for param 2
}
};
private final Pattern regex;
private MyEnum(String strRegex) {
this.regex = Pattern.compile(strRegex);
}
public abstract void doSomething();
public static MyEnum valueFor(String value) {
for (MyEnum myEnum : MyEnum.values()) {
if(myEnum.regex.matcher(value).matches()) {
return myEnum;
}
}
return null;
}
}
您可以看到IDEOne demo。