Java正则表达式分别匹配字符串和子字符串

时间:2018-01-10 12:16:06

标签: java regex regex-group

下面是一个更大场景的一部分,我正在尝试编写一个表达式来识别左操作数和后续操作符。

代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExTest1 {

    public static void main (String args[] ) {

        String input[] = { "namein", 
                        "namenotin"};

        String operatorExpr = "(?<operator>(in)|(notin))";
        String conditionExpr ="(?<operand1>\\S+)"+  operatorExpr;

        Pattern p = Pattern.compile(conditionExpr);

        for(String in: input) {

            Matcher m = p.matcher(in);
            if (m.find()) {

                String operand1 = m.group("operand1");
                String operator = m.group("operator");
                System.out.println("Input: \""+in + "\" | Operand1 : \""+ operand1 + "\"" + "| Operator : \""+ operator + "\"");

            }
        }

    }

}

实际输出:

Input: "namein" | Operand1 : "name"| Operator : "in"
Input: "namenotin" | Operand1 : "namenot"| Operator : "in"

预期产出:

Input: "namein" | Operand1 : "name"| Operator : "in"
Input: "namenotin" | Operand1 : "name"| Operator : "notin"

我在这里写的表达式没有返回预期的输出,当我们有一个字符串和子字符串匹配或'|'量词

“在| notin”

一旦我确定两个匹配组互相排斥,如“ein | notin”,就会返回预期的值。

但要求是让它也适用于当前的场景。

1 个答案:

答案 0 :(得分:0)

尝试以下

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExTest1 {

    public static void main (String args[] ) {

        String input[] = { "namein", "namenotin"};

        String operatorExpr = "(?<operator>(in)|(notin))";
        String conditionExpr ="(?<operand1>\\S+?)"+  operatorExpr;

        Pattern p = Pattern.compile(conditionExpr);

        for(String in: input) {

            Matcher m = p.matcher(in);
            if (m.find()) {

                String operand1 = m.group("operand1");
                String operator = m.group("operator");
                System.out.println("Input: \""+in + "\" | Operand1 : \""+ operand1 + "\"" + "| Operator : \""+ operator + "\"");

            }
        }

    }

}