gpt4 book ai didi

java - 用多个特殊字符拆分 : √(A&B)

转载 作者:行者123 更新时间:2023-11-30 10:58:23 26 4
gpt4 key购买 nike

我有√(A&B)=|C|等式,

拆分后,我得到这个值

[√, (, A&B, ),=,|, C,|]

如何获得这样的值(value)

[√(, A&B, ),=,|, C,|]

这是我的代码,

return teks.split(""
+ "((?<=\\ )|(?=\\ ))|"
+ "((?<=\\!)|(?=\\!))|"
+ "((?<=\\√\\()|(?=\\√\\())|" //this is my problem
+ "((?<=\\√)|(?=\\√))|" //and this
+ "((?<=\\∛)|(?=\\∛))|"
+ "((?<=\\/)|(?=\\|))"
+ "((?<=\\&)|(?=\\&))"
+ "");
}

最佳答案

尝试使用 Matcher.find() 获取以下正则表达式:

String s = "√(A&B)=|C|";
Matcher m = Pattern.compile("("
+ "(√\\()"
+ "|(\\))"
+ "|(\\w(\\&\\w)*)"
+ "|(=)"
+ "|(\\|)"
+ ")").matcher(s);

ArrayList<String> r = new ArrayList<>();
while(m.find())
r.add(m.group(1));

System.out.printf("%s", r.toString());

结果:

[√(, A&B, ), =, |, C, |]

更新。

或者,如果括号前的任何符号(“=”除外)应该与那个“(”算作一个符号:

String s = "√(A&(B&C))=(|C| & (! D))";

Matcher m = Pattern.compile("("
+ "[^\\s=]?\\(" // capture opening bracket with modifier (if any)
// you can replace it with "[√]?\\(", if only
// "√" symbol should go in conjunction with brace
+ "|\\)" // capture closing bracket
+ "|\\w" // capture identifiers
+ "|[=!\\&\\|]" // capture symbols "=", "!", "&" and "|"
+ ")").matcher(s.replaceAll("\\s", ""));

ArrayList<String> r = new ArrayList<>();
while(m.find())
r.add(m.group(1));

System.out.printf("%s -> %s\n", s, r.toString().replaceAll(", ", ",")); // ArrayList joins it's elements with ", ", so, removing extra space

结果:

√(A&(B&C))=(|C| & (! D)) -> [√(,A,&(,B,&,C,),),=,(,|,C,|,&(,!,D,),)]

关于java - 用多个特殊字符拆分 : √(A&B),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32283479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com