kun*_*ora 59 java regex string
我有一个String变量,str可能的值val1,val2和val3.
我想str使用if语句比较(相同的情况)所有这些值,例如:
if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3.equalsIgnoreCase(str))
{
//remaining code
}
Run Code Online (Sandbox Code Playgroud)
有没有办法避免使用多个OR(||)运算符并比较一个表达式中的值?例如,像这样:
if(("val1" OR "val2" OR "val3").equalsIgnoreCase(str) //this is only an idea.
Run Code Online (Sandbox Code Playgroud)
kun*_*ora 93
我找到了更好的解决方案.这可以通过RegEx来实现:
if (str.matches("val1|val2|val3")) {
// remaining code
}
Run Code Online (Sandbox Code Playgroud)
对于不区分大小写的匹配:
if (str.matches("(?i)val1|val2|val3")) {
// remaining code
}
Run Code Online (Sandbox Code Playgroud)
Ell*_*sch 61
在Java 8+中,您可以使用Stream<T>和anyMatch(Predicate<? super T>)类似的东西
if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
hmj*_*mjd 15
您可以将要比较的所有字符串存储str到集合中,并检查集合是否包含str.将集合中的所有字符串存储为小写,并str在查询集合之前转换为小写.例如:
Set<String> strings = new HashSet<String>();
strings.add("val1");
strings.add("val2");
String str = "Val1";
if (strings.contains(str.toLowerCase()))
{
}
Run Code Online (Sandbox Code Playgroud)
另一种选择(有点类似于上面的/sf/answers/2256913991/)使用 apache 公共库中的 StringUtils:https : //commons.apache.org/proper/commons-lang/apidocs/org/ apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-
if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
// remaining code
}
Run Code Online (Sandbox Code Playgroud)
这是具有多个替代方案的性能测试(有些区分大小写,有些不区分大小写):
public static void main(String[] args) {
// Why 4 * 4:
// The test contains 3 values (val1, val2 and val3). Checking 4 combinations will check the match on all values, and the non match;
// Try 4 times: lowercase, UPPERCASE, prefix + lowercase, prefix + UPPERCASE;
final int NUMBER_OF_TESTS = 4 * 4;
final int EXCUTIONS_BY_TEST = 1_000_000;
int numberOfMatches;
int numberOfExpectedCaseSensitiveMatches;
int numberOfExpectedCaseInsensitiveMatches;
// Start at -1, because the first execution is always slower, and should be ignored!
for (int i = -1; i < NUMBER_OF_TESTS; i++) {
int iInsensitive = i % 4;
List<String> testType = new ArrayList<>();
List<Long> timeSteps = new ArrayList<>();
String name = (i / 4 > 1 ? "dummyPrefix" : "") + ((i / 4) % 2 == 0 ? "val" : "VAL" )+iInsensitive ;
numberOfExpectedCaseSensitiveMatches = 1 <= i && i <= 3 ? EXCUTIONS_BY_TEST : 0;
numberOfExpectedCaseInsensitiveMatches = 1 <= iInsensitive && iInsensitive <= 3 && i / 4 <= 1 ? EXCUTIONS_BY_TEST : 0;
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("List (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Arrays.asList("val1", "val2", "val3").contains(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Set (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (new HashSet<>(Arrays.asList(new String[] {"val1", "val2", "val3"})).contains(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("OR (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if ("val1".equals(name) || "val2".equals(name) || "val3".equals(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("OR (Case insensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if ("val1".equalsIgnoreCase(name) || "val2".equalsIgnoreCase(name) || "val3".equalsIgnoreCase(name)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("ArraysBinarySearch(Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Arrays.binarySearch(new String[]{"val1", "val2", "val3"}, name) >= 0) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Java8 Stream (Case sensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Stream.of("val1", "val2", "val3").anyMatch(name::equals)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("Java8 Stream (Case insensitive)");
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (Stream.of("val1", "val2", "val3").anyMatch(name::equalsIgnoreCase)) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("RegEx (Case sensitive)");
// WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (name.matches("val1|val2|val3")) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("RegEx (Case insensitive)");
// WARNING: if values contains special characters, that should be escaped by Pattern.quote(String)
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
if (name.matches("(?i)val1|val2|val3")) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseInsensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
numberOfMatches = 0;
testType.add("StringIndexOf (Case sensitive)");
// WARNING: the string to be matched should not contains the SEPARATOR!
final String SEPARATOR = ",";
for (int j = 0; j < EXCUTIONS_BY_TEST; j++) {
// Don't forget the SEPARATOR at the begin and at the end!
if ((SEPARATOR+"val1"+SEPARATOR+"val2"+SEPARATOR+"val3"+SEPARATOR).indexOf(SEPARATOR + name + SEPARATOR)>=0) {
numberOfMatches++;
}
}
if (numberOfMatches != numberOfExpectedCaseSensitiveMatches) {
throw new RuntimeException();
}
timeSteps.add(System.currentTimeMillis());
//-----------------------------------------
StringBuffer sb = new StringBuffer("Test ").append(i)
.append("{ name : ").append(name)
.append(", numberOfExpectedCaseSensitiveMatches : ").append(numberOfExpectedCaseSensitiveMatches)
.append(", numberOfExpectedCaseInsensitiveMatches : ").append(numberOfExpectedCaseInsensitiveMatches)
.append(" }:\n");
for (int j = 0; j < testType.size(); j++) {
sb.append(String.format(" %4d ms with %s\n", timeSteps.get(j + 1)-timeSteps.get(j), testType.get(j)));
}
System.out.println(sb.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
输出(仅在最坏的情况下,即必须检查所有元素而没有 match none 时):
Test 4{ name : VAL0, numberOfExpectedCaseSensitiveMatches : 0, numberOfExpectedCaseInsensitiveMatches : 0 }:
43 ms with List (Case sensitive)
378 ms with Set (Case sensitive)
22 ms with OR (Case sensitive)
254 ms with OR (Case insensitive)
35 ms with ArraysBinarySearch(Case sensitive)
266 ms with Java8 Stream (Case sensitive)
531 ms with Java8 Stream (Case insensitive)
1009 ms with RegEx (Case sensitive)
1201 ms with RegEx (Case insensitive)
107 ms with StringIndexOf (Case sensitive)
Run Code Online (Sandbox Code Playgroud)
Warpspeed SCP 提供的输出,更改测试以填充循环外的集合,当要测试的值列表永远不会改变时模拟代码(并且可以缓存集合)。
(本次测试的时间不要与之前的测试进行比较,因为它是在不同的环境下执行的,而只比较同一测试不同策略的时间):
Test 4{ name : VAL0, numberOfExpectedCaseSensitiveMatches : 0, numberOfExpectedCaseInsensitiveMatches : 0 }:
26 ms with List (Case sensitive)
6 ms with Set (Case sensitive)
12 ms with OR (Case sensitive)
371 ms with OR (Case insensitive)
14 ms with ArraysBinarySearch(Case sensitive)
100 ms with Java8 Stream (Case sensitive)
214 ms with Java8 Stream (Case insensitive)
773 ms with RegEx (Case sensitive)
946 ms with RegEx (Case insensitive)
37 ms with StringIndexOf (Case sensitive)
Run Code Online (Sandbox Code Playgroud)
ArrayUtils 可能会有所帮助。
ArrayUtils.contains(new String[]{"1", "2"}, "1")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86004 次 |
| 最近记录: |