对于规则
a==b&c>=d|e<=f&!x==y
我想使用 &,|,& 来拆分规则!operator andt 还想存储运算符。
所以我想存储:
a==b
&
c>=d
|
e<=f
&!
x==y
我还应该将其存储在字符串数组中吗?
谢谢。
对于规则
a==b&c>=d|e<=f&!x==y
我想使用 &,|,& 来拆分规则!operator andt 还想存储运算符。
所以我想存储:
a==b
&
c>=d
|
e<=f
&!
x==y
我还应该将其存储在字符串数组中吗?
谢谢。
它可以在单行中实现,但它会涉及一个相当复杂的正则表达式,同时使用前瞻和后瞻。
str.split("(?<=&!?|\\|)|(?=&!?|\\|)");
那么这个正则表达式有什么作用呢?
正则表达式&!?|\|
根据您的规则定义什么是有效运算符。它基本上读作“和&
-sign 可选地后跟!
-sign,或|
-sign”。
其他部分是正则表达式构造lookahead 和lookbehind,即所谓的“零宽度断言”。
(?=a)
是一个向前看,它向前看并确保下一个字符是“a”。例如,它匹配在“foobar”中的“b”和“a”之间开始和结束的零长度字符串。
因此,使用给定的正则表达式参数,我提出的 split 方法调用基本上可以:
在输入字符串中紧接在 a &
、 a&!
或|
符号之前或之后的每个位置拆分。
这个正则表达式做你想要的..
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
试试这个方法
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