我有一个动态生成的字符串.
我需要根据Relational Operator拆分字符串.
为此,我可以使用分割功能.
现在我还想知道上面提到的正则表达式,基于哪个Relational Operator是实际拆分的字符串.
一个例子,
在输入
String sb = "FEES > 200";
应用
List<String> ls = sb.split(">|>=|<|<=|<>|="); System.out.println("Splitted Strings: "+s);
会给我结果,
Splitted strings: [FEES,200 ]
但期待结果:
Splitted strings: [FEES,200 ] Splitted Relational Operator: >
解决方法
您可以使用3个捕获组,并为第二组更改:
(*?)(大于= |< = |<> |> |≤)(*).
说明
>(.*?)匹配任何字符零次或多次非贪婪
>(> = |< = |<> |> |<)匹配> =或< =或<>或>或者<
>(.*)匹配任何字符零次或多次
例如:
String regex = "(.*?)(>=|<=|<>|>|<)(.*)"; String string = "FEES >= 200"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(string); if(matcher.find()) { System.out.println("Splitted Relational Operator: " + matcher.group(2)); System.out.println("Group 1: " + matcher.group(1) + " group 3: " + matcher.group(3)); }