Java Tutorial/Development/Matcher
Версия от 17:44, 31 мая 2010; (обсуждение)
Matcher Find
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
public static void main(String[] args) {
Matcher m = Pattern.rupile("\\w+").matcher("Today is Sunday");
while (m.find())
System.out.println(m.group());
int i = 0;
while (m.find(i)) {
System.out.print(m.group() + " ");
i++;
}
}
}
/* */
Today is Sunday Today oday day ay y is is s Sunday Sunday unday nday day ay y
Matcher.LookingAt
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
public static void main(String[] args) {
String[] input = new String[] { "Java has regular expressions in 1.4",
"regular expressions now expressing in Java", "Java represses oracular expressions" };
Pattern p1 = Pattern.rupile("re\\w*"), p2 = Pattern.rupile("Java.*");
for (int i = 0; i < input.length; i++) {
System.out.println("input " + i + ": " + input[i]);
Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
if (m1.lookingAt()) // No reset() necessary
System.out.println("m1.lookingAt() start = " + m1.start() + " end = " + m1.end());
}
}
}
/*
*/
input 0: Java has regular expressions in 1.4 input 1: regular expressions now expressing in Java m1.lookingAt() start = 0 end = 7 input 2: Java represses oracular expressions
Matcher Start and End
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
public static void main(String[] args) {
String[] input = new String[] { "Java has regular expressions in 1.4",
"regular expressions now expressing in Java", "Java represses oracular expressions" };
Pattern p1 = Pattern.rupile("re\\w*"), p2 = Pattern.rupile("Java.*");
for (int i = 0; i < input.length; i++) {
System.out.println("input " + i + ": " + input[i]);
Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
while (m1.find())
System.out.println("m1.find() "" + m1.group() + "" start = " + m1.start() + " end = "
+ m1.end());
}
}
}
/*
*/
input 0: Java has regular expressions in 1.4 m1.find() "regular" start = 9 end = 16 m1.find() "ressions" start = 20 end = 28 input 1: regular expressions now expressing in Java m1.find() "regular" start = 0 end = 7 m1.find() "ressions" start = 11 end = 19 m1.find() "ressing" start = 27 end = 34 input 2: Java represses oracular expressions m1.find() "represses" start = 5 end = 14 m1.find() "ressions" start = 27 end = 35