Java/Regular Expressions/Greedy

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

Greedy and Nongreedy Matching in a Regular Expression

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Greedy quantifiers
    String match = find("A.*c", "AbcAbc"); 
    match = find("A.+", "AbcAbc"); 
  }
  public static String find(String patternStr, CharSequence input) {
    Pattern pattern = Pattern.rupile(patternStr);
    Matcher matcher = pattern.matcher(input);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }
}





Greedy Qualifier

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main  {
  public static void main(String args[]) {
    String regex = "(\\w+)(\\d\\d)(\\w+)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "X99 asdf 44";
    Matcher matcher = pattern.matcher(candidate);
    matcher.find();
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
  }
}





Nongreedy quantifiers

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Nongreedy quantifiers
    String match = find("A.*?c", "AbcAbc"); 
    match = find("A.+?", "AbcAbc"); 
  }
  public static String find(String patternStr, CharSequence input) {
    Pattern pattern = Pattern.rupile(patternStr);
    Matcher matcher = pattern.matcher(input);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }
}





Reluctant Qualifier Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
  public static void main(String args[]) {
    String regex = "(\\d+?)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "1234";
    Matcher matcher = pattern.matcher(candidate);
    while (matcher.find()) {
      System.out.println(matcher.group());
    }
    System.out.println("Done");
  }
}