Java Tutorial/Regular Expressions/Group — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:19, 31 мая 2010

A simple sub group

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("\\w(\\d)");
    String candidate = "A6 is Audi";
    Matcher matcher = p.matcher(candidate);
    if (matcher.find()) {
      String tmp = matcher.group(0);
      System.out.println(tmp);
      tmp = matcher.group(1);
      System.out.println(tmp);
    }
  }
}





Finding Every Occurrence of the Letter A

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindA {
  public static void main(String args[]) throws Exception {
    String candidate = "A Matcher examines the results of applying a pattern.";
    String regex = "\\ba\\w*\\b";
    Pattern p = Pattern.rupile(regex);
    Matcher m = p.matcher(candidate);
    String val = null;
    System.out.println("INPUT: " + candidate);
    System.out.println("REGEX: " + regex + "\r\n");
    while (m.find()) {
      val = m.group();
      System.out.println("MATCH: " + val);
    }
    if (val == null) {
      System.out.println("NO MATCHES: ");
    }
  }
}





Find the end point of the first sub group (ond)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("B(on)d");
    String candidateString = "My name is Bond. James Bond.";
    String matchHelper[] = { "               ^", "              ^", "                           ^",
        "                          ^" };
    Matcher matcher = p.matcher(candidateString);
//  find the end point of the first sub group (ond)
    int nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);

  }
}





Working with simple groups

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("\\w\\d");
    String candidate = "A6 is my favorite";
    Matcher matcher = p.matcher(candidate);
    if (matcher.find()) {
      String tmp = matcher.group(0);
      System.out.println(tmp);
    }
  }
}