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

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was places for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

I want to knew how the Pattern and Matcher object works ?

I reffered few examples but i cant come up with that.

rcgoncalves
  • 128
  • 6
09Q71AO534
  • 4,300
  • 13
  • 44
  • 68
  • what does the pattern does and what does the Matcher do..How wil the find and group work. – 09Q71AO534 Aug 01 '13 at 09:36
  • 1
    The groups are numbered from **1**, `m.group() == m.group(0)` is the entire match of all. `.find()` is for (repeated) searches, `.matches()` for a single match for the entire string. – Joop Eggen Aug 01 '13 at 09:37
  • What does the group(\\d+) do..which pattern will it look for.. – 09Q71AO534 Aug 01 '13 at 09:39
  • 1
    possible duplicate of [A Java regular expression about finding digit string](http://stackoverflow.com/questions/11434913/a-java-regular-expression-about-finding-digit-string) and also: http://stackoverflow.com/questions/17969436/java-regex-capturing-groups – assylias Aug 01 '13 at 09:39
  • One or more (postfix `+`) of a digit `\d`. See [Pattern](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) – Joop Eggen Aug 01 '13 at 09:40
  • Thank u Everyone ;-) for this support – 09Q71AO534 Aug 01 '13 at 09:42

2 Answers2

1

Your groups start from index = 1. Zero is an index for a whole match.

So, the first (.*) is in m.group(1), (\\\d+) is in m.group(2), and the second (.*) is in m.group(3)

0

http://www.regular-expressions.info/tutorial.html contains pretty much everything you need to know about regular expressions

RokL
  • 2,663
  • 3
  • 22
  • 26