对于规则
a==b&c>=d|e<=f&!x==y
我想使用&amp;,|,&amp;!来拆分规则operator andt也想存储运算符。
所以我想存储:
a==b
&
c>=d
|
e<=f
&!
x==y
还应该将它存储在字符串数组中吗?
感谢。
答案 0 :(得分:0)
试试这种方式
String data = "a==b&c>=d|e<=f&!x==y";
Pattern p = Pattern.compile(
"&!"+ // &!
"|" + // OR
"&" + // &
"|" + // OR
"\\|" // since | in regex is OR we need to use to backslashes
// before it -> \\| to turn off its special meaning
);
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(data);
while(m.find()){
m.appendReplacement(sb, "\n"+m.group()+"\n");
}
m.appendTail(sb);
System.out.println(sb);
输出
a==b
&
c>=d
|
e<=f
&!
x==y
答案 1 :(得分:0)
这个正则表达式做你想要的......
final String input = "a==b&c>=d|e<=f&!x==y";
//this regex will yield pairs of one string followed by operator (&, | or &!)...
final String mainRegex = "(.*?)(&!|&|\\|)";
final Matcher matcher = Pattern.compile(mainRegex).matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
//...so we will need another regex to fetch what comes after the last operator
final String lastOne = "(.*)(&|\\||!)(.*)";
final Matcher lastOneMatcher = Pattern.compile(lastOne).matcher(input);
if (lastOneMatcher.find()) {
System.out.println(lastOneMatcher.group(3));
}
结果:
a==b
&
c>=d
|
e<=f
&!
x==y