0

Below is part of a bigger scenario where I'm trying to write an expression to identify the left operand and the subsequent operator.

Code:

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 + "\"");

            }
        }

    }

}

Actual output:

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

Expected output:

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

The expressions I wrote here are not returning expected output when we have a string and substring matching both against the or '|' quantifier

"in|notin"

As soon as I made sure both the matching groups are mutually exclusive of one another like "ein|notin", expected values are returned.

But the requirement is to make it work on current scenario as well.

ImGroot
  • 796
  • 1
  • 6
  • 17
  • `\S+` greedily matches the whole string, then backtracks until it matches either `in` or `notin`. Make it lazy instead -> `\S+?` – Sebastian Proske Jan 10 '18 at 12:20
  • @SebastianProske It works..Thank you!! Could you please add more detail to the backtracking mechanism with "?" – ImGroot Jan 10 '18 at 12:30

1 Answers1

0

Try following

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 + "\"");

            }
        }

    }

}
axnet
  • 5,146
  • 3
  • 25
  • 45