/*
 * [TestRegexFindWithOr.java]
 *
 * Summary: Finding with a Regex using "or" (|).
 *
 * Copyright: (c) 2011-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2011-03-15 initial release
 */
package com.mindprod.example;

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

import static java.lang.System.*;

/**
 * Finding with a Regex using "or" (|).
 * <p/>
 * Use an or-style regex to find instances of the pattern embedded in a large string .
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2011-03-15 initial release
 * @since 2011-03-15
 */
public class TestRegexFindWithOr
    {
    /**
     * Regex we look for embedded in big string. By default case-sensitive.
     */
    private static final Pattern PATTERN1 = Pattern.compile( "The (wolf|puppy|dog) is" );

    /**
     * Regex we look for embedded in big string. By default case-sensitive. Adds extra ()
     */
    private static final Pattern PATTERN2 = Pattern.compile( "The ((wolf)|(puppy)|(dog)) is" );

    /**
     * test harness
     *
     * @param args not used
     */
    public static void main( String[] args )
        {
        final String lookIn = "Monkeys are messy. The puppy is ephemeral. The elephant requires a lot of space.";
        final Matcher m1 = PATTERN1.matcher( lookIn );  // Matchers are used both for matching and finding.
        while ( m1.find() )
            {
            final int gc = m1.groupCount();
            // group 0 is the whole pattern matched,
            // loops runs from from 0 to gc, not 0 to gc-1 as is traditional.
            for ( int i = 0; i <= gc; i++ )
                {
                out.println( i + " : " + m1.group( i ) );
                }
            // prints
            // 0 : The puppy is : whole thing
            // 1 : puppy : () around triple
            }
        // redo with extra layer of ()
        final Matcher m2 = PATTERN2.matcher( lookIn );
        while ( m2.find() )
            {
            final int gc = m2.groupCount();
            for ( int i = 0; i <= gc; i++ )
                {
                out.println( i + " : " + m2.group( i ) );
                }
            // prints
            // 0 : The puppy is : whole thing
            // 1 : puppy : () around triple
            // 2 : null :  (wolf)
            // 3 : puppy : (puppy)
            // 4 : null  : (dog)
            }
        }
    }