Java Tutorial/Regular Expressions/Group
Содержание
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);
}
}
}