package com.mindprod.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* test indexOfRegex to search a string for the first instance of a given pattern.
* <p/>
* Prepared with IntelliJ Idea.
*
* @author Roedy Green, Canadian Mind Products, based on an example posted by Knute Johnson
* @version 1.0, 2008-01-29
*/
public class TestIndexOfRegex
{
/**
* regex pattern to look for, in this case whitespace
*/
private static final Pattern lookFor = Pattern.compile( "\\s+" );
/**
* Scan a string for the first occurence 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 indexOfRegex( String lookIn,
Pattern lookFor )
{
Matcher m = lookFor.matcher( lookIn );
if ( m.find() )
{
return m.start();
}
else
{
return -1;
}
}
public static void main( String[] args )
{
String lookIn = "The quick brown fox jumped\n"
+ "over the lazy dog's back.";
System.out.println( indexOfRegex( lookIn, lookFor ) );
}
}