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

时间:2015-08-29 06:53:55

标签: java regex

我有getParseGeoPoint("String");等式,

分裂后,我得到这个值

√(A&B)=|C|

如何获得这样的价值

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

这是我的代码,

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

1 个答案:

答案 0 :(得分:1)

尝试使用Matcher.find()跟随regexp:

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, |]

<强> UPD。

或者,如果括号前的任何符号(“=”除外)应计为一个符号“(”:

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,),)]