如何实现Spring表达式语言(SpEL)大小写不敏感求值及包含判断
SpEL实现大小写不敏感求值与字符串包含判断
一、大小写不敏感求值
有两种简洁的实现方式:
方式1:使用String的equalsIgnoreCase方法
直接在SpEL表达式中调用字符串的equalsIgnoreCase方法,该方法原生支持大小写不敏感的字符串比较:
Car car = new Car(); car.setMake("tesla"); car.setOwner("abc"); // 改用equalsIgnoreCase做大小写不敏感比较 String expressionString = "(make.equalsIgnoreCase('TESLA') && owner.equalsIgnoreCase('ABC'))"; ExpressionParser expressionParser = new SpelExpressionParser(); Expression expression = expressionParser.parseExpression(expressionString); Boolean result = expression.getValue(car, Boolean.class); System.out.println("matching? " + result); // 输出true
方式2:统一转换为大写/小写后比较
通过toUpperCase()或toLowerCase()方法将两边字符串统一大小写后再做相等判断:
String expressionString = "(make.toUpperCase() == 'TESLA' && owner.toUpperCase() == 'ABC')"; // 执行后结果同样为true
二、字符串包含判断
直接调用String的contains()方法即可实现包含判断,如果需要大小写不敏感的包含逻辑,可结合大小写转换实现:
普通包含判断
car.setOwner("abcdef"); String expressionString = "owner.contains('cde')"; Boolean result = expression.getValue(car, Boolean.class); System.out.println("contains? " + result); // 输出true
大小写不敏感的包含判断
car.setOwner("AbCdEf"); String expressionString = "owner.toLowerCase().contains('cde'.toLowerCase())"; Boolean result = expression.getValue(car, Boolean.class); System.out.println("case-insensitive contains? " + result); // 输出true
内容的提问来源于stack exchange,提问作者sabu
相关产品推荐
相关产品推荐

