正则表达式基于逻辑运算符拆分字符串

时间:2018-01-17 06:17:48

标签: java regex split

我有一个像这样的表达

String x = ".pyValue='2||3'||.pxValue='5'"

我想基于像"和"这样的逻辑运算符来拆分这个字符串。和"或"使用正则表达式。

String a = ".pyValue='2||3'"
String b = ".pxValue='5'"

或字符串可能是这样的

String x = ".pyValue='2||3'||.pxValue='2' && .pxValue=3 && .pxValue='2&&3'"

输出应该是这样的

String a = ".pyValue='2||3'"
String b = ".pxValue='2'"
String c = ".pxValue=3"
String d = ".pxValue='2&&3'"

2 个答案:

答案 0 :(得分:0)

这个常规可以帮助你:

(?<=')\s?(\|{2}|\&{2})\s?

但是你应该注意参数名称,所有参数必须以.字符开头。

使用:

    String data = ".pyValue='2||3'||.pxValue='2' &| .pxValue=3 && .pxValue='2&&3'";

    String[] array = data.split("(?<=')\\s?(\\|{2}|\\&{2})\\s?");

    for(String string : array){
        System.out.println(string);
    }

结果:

.pyValue='2||3'
.pxValue='2'
.pxValue=3
.pxValue='2&&3'

答案 1 :(得分:-1)

We've to provide list of 'Operands', for example 

    [0-9]|[a-z]|[A-Z]|\|\||&&|\(|\)

Each operand is separaed by '|', we can escape some operands which are keywords by adding \. 


For example:

String pattern = "(?<![&|])(?=[&|])|(?<=[&|])(?![&|])";


String input = "a&&(b||c)";
String[] array = input.split(pattern);
System.out.println(Arrays.asList(array));
Prints: [a, &&, (b, ||, c)] 

有关详细信息,请查看 - RegEx to split string based on operators and retain operator in answer