先看结果:处理字符串
"这个是一条测试用的字符串[ ( 5 ( 4( 3 [(1) (2)] ))(7))][(6)]"
结果
解决思路:参考正则表达式里面出入站部分
代码实现如下:
方法调用“:
String test = "这个是一条测试用的字符串[ ( 5( 4( 3 [(1) (2)] ))(7))][(6)]"; LinkedHashMap<Integer, Integer> linkedHashMap = getBracketPairs(test, '('); System.out.println(JSON.toJSONString(linkedHashMap));
//此处value+1可以 把)也打印出来 默认 substring 不包含右侧末尾位置
linkedHashMap.forEach((key, value) -> System.out.println(test.substring(key, value+1)));
/**
* <p> 获取对应的括号组位置 </p>
* 例如{37:39,26:28,43:45,30:32,21:35,18:36,15:40}
* @param string 字符串
* @param symbolLeft 左侧符号 内置三类 ( [ {
* @return {@link LinkedHashMap }<{@link Integer }, {@link Integer }>
* @author xhūnchéng Xú
* @since 0.0.1 2023-07-03
*/
private static LinkedHashMap<Integer, Integer> getBracketPairs(String string, Character symbolLeft) { Map<Character, Character> characterHashMap = new HashMap<>(); characterHashMap.put('(', ')'); characterHashMap.put('[', ']'); characterHashMap.put('{', '}'); Character symbolRight = characterHashMap.get(symbolLeft); if (symbolRight == null || symbolRight.toString().length() < 1) { return new LinkedHashMap<>(); } char[] strArray = string.toCharArray(); //找到所有左右()的位置 ArrayList<Integer> right = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < strArray.length; i++) { if (strArray[i] == symbolLeft) { list.add(i); } else if (strArray[i] == symbolRight) { right.add(i); list.add(i); } } LinkedList<Integer> linkedList = new LinkedList<>(); Map<Integer, Integer> integerMap = new HashMap<>(); for (int a : list) { boolean contains = right.stream().anyMatch(x -> x == a); if (!contains) { linkedList.add(a); } else { if (linkedList.size() > 0) { Integer leInt = linkedList.get(linkedList.size() - 1); integerMap.put(leInt, a); linkedList.removeLast(); } } } return integerMap.entrySet().stream() .sorted((o1, o2) -> { int c1 = o1.getValue() - o1.getKey(); int c2 = o2.getValue() - o2.getKey(); return Integer.compare(c1, c2); }) .collect(LinkedHashMap::new, (map, entry) -> { map.put(entry.getKey(), entry.getValue()); }, LinkedHashMap::putAll); }
由于目的是进行SQL脚本适配;当前排序只排序最小单元 可自定义按需配置 即 sorted 部分
参考文章思路:正则表达式匹配对称小括号 - 曹万军 - 博客园 (cnblogs.com)