/*
 * [TestRegexIndexOf.java]
 *
 * Summary: Search a string for the first instance of a given regex pattern.
 *
 * Copyright: (c) 2009-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 2008-01-29
 */
package com.mindprod.example;

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

import static java.lang.System.*;

/**
 * Search a string for the first instance of a given regex pattern.
 * <p/>
 * Prepared with IntelliJ Idea.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2008-01-29
 * @since 2008-01-29
 */
public class TestRegexIndexOf
    {
    /**
     * regex pattern to look for, in this case whitespace
     */
    private static final Pattern lookFor = Pattern.compile( "\\s+" );

    public static void main( String[] args )
        {
        String lookIn = "The quick brown fox jumped\n"
                        + "over the lazy dog's back.";
        out.println( regexIndexOf( lookIn, lookFor ) );
        // prints 3
        }

    /**
     * Scan a string for the first occurrence of some regex Pattern.
     *
     * @param lookFor the pattern to look for
     * @param lookIn  the String to scan.
     *
     * @return offset relative to start of lookIn where it first found the pattern, -1 if not found.
     */
    @SuppressWarnings( { "SameParameterValue", "WeakerAccess" } )
    public static int regexIndexOf( String lookIn,
                                    Pattern lookFor )
        {
        Matcher m = lookFor.matcher( lookIn );
        if ( m.find() )
            {
            return m.start();
            }
        else
            {
            return -1;
            }
        }
    }