1、需求
给定区间字符串,例如 [2,3) 我们可以返回某个字段 a >= 2 and a < 3
2、具体实现
1. /** 2. * 解析区间字符串--[1,2) -> a >= 1 and a < 2 3. * @author QiJingJing 4. * @since 2023/2/23 5. */ 6. public class IntervalFormatUtil { 7. public static String intervalToCondition(String intervalStr, String name) { 8. if (intervalStr == null || intervalStr.isEmpty() || name == null || name.isEmpty()) { 9. return ""; 10. } 11. 12. // 解析区间字符串 13. boolean startInclusive = intervalStr.charAt(0) == '['; 14. boolean endInclusive = intervalStr.charAt(intervalStr.length() - 1) == ']'; 15. String[] parts = intervalStr.substring(1, intervalStr.length() - 1).split(","); 16. if (parts.length != 2) { 17. return ""; 18. } 19. String start = parts[0].trim(); 20. String end = parts[1].trim(); 21. 22. // 构建条件语句并返回 23. return name + " " + (startInclusive ? ">=" : ">") + " " + start + " and " + name + " " + (endInclusive ? "<=" : "<") + " " + end; 24. } 25. 26. }
3、测试
1. System.out.println(IntervalFormatUtil.intervalToCondition("[2,3]", "abc")); 2. System.out.println(IntervalFormatUtil.intervalToCondition("(2,3)", "abc")); 3. System.out.println(IntervalFormatUtil.intervalToCondition("(2,3]", "abc"));
结果:
1. abc >= 2 and abc <= 3 2. abc > 2 and abc < 3 3. abc > 2 and abc <= 3