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

标签 java regex

我有√(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/

相关文章:

Java 不大于或等于 Char 类型的运算符

java - 将字符串数组转换为列表 : double brackets

java - 如何为类的每个实例分配一个唯一的序列号?

java - 如何最好地访问模式中捕获组的数量?

regex - Perl 一行代码将第一个字符转换为大写 - 逻辑理解

php - 正则表达式匹配每个字符和换行符

java - Android 数据绑定(bind)单选组

java - 如何检查 Collection 是否至少包含 google-truth 中的 N 个匹配元素?

regex - perl6正则表达式匹配连词&&

javascript - 用于匹配用户名的正则表达式 : min 3 chars, 最多 20 个字符,字符之间可选下划线