Regex grouping and matching
<p>I have a regex <a href="https://regex101.com/r/PPbhRn/1" rel="nofollow noreferrer">https://regex101.com/r/PPbhRn/1</a>. Here i see that when "and" is captured, i am able to see some white spaces also captured above. Is there any way to get rid of that white spaces? and i want to know whether the pattern will match only when grouping is captured correctly?</p>

<pre><code>String validRegex="(((?:[(]* ?[a-z][a-z]+ ?[)]*)|[(]* ?(NOT) (?:[(]* ?[a-z][a-z]+ ?[)]*) ?[)]*)( (AND|OR) ((?:[(]* ?[a-z][a-z]+ ?[)]*)|[(]* ?(NOT) (?:[(]* ?[a-z][a-z]+ ?[)]*) ?[)]*))*)";

    String formula = "mean AND trip OR (mean OR mango) AND (mean AND orange) OR mango AND (test OR NOT help)";
    Pattern p1 = Pattern.compile(validRegex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
    final Matcher matcher = p1.matcher(formula);

    boolean result=MarketMeasureUtil.isValidFormula(formula);
    System.out.println(result);

    while (matcher.find()) {
        System.out.println("Full match: " + matcher.group(0));
        for (int i = 1; i &lt;= matcher.groupCount(); i++) {
            System.out.println("Group " + i + ": " + matcher.group(i));
            System.out.println( matcher.group() + "starting at" + "index" + matcher.start()+ "and ending at index" +matcher.end() );

        }
</code></pre>

<p>I'm not able to capture the groups properly, i need to capture groups like "mean AND trip" "OR" "mean or mango"..etc..
isValidFormula() invokes the regex.matches(). In our case matches works fine. Grouping is not working as expected</p>