Pattern matcher
package com.minte9.basics.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pattern_matcher {
public static void main(String[] args) {
Pattern p = Pattern.compile("Version");
Matcher m = p.matcher("Version 1.0");
Boolean match_exactly = m.matches();
Boolean found_parts = m.find();
System.out.println(match_exactly);
System.out.println(found_parts);
}
}
Greedy
package com.minte9.basics.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Greedy {
public static void main(String[] args) {
Pattern p;
Matcher m;
String txt = "extend cup end table";
p = Pattern.compile("e.+d");
m = p.matcher(txt);
while(m.find()) {
System.out.println(m.group());
}
p = Pattern.compile("e.+?d");
m = p.matcher(txt);
while(m.find()) {
System.out.println(m.group());
}
p = Pattern.compile("Java ?(8|SE)");
m = p.matcher("Java 8 Java SE");
while(m.find()) {
System.out.println(m.group());
}
}
}
Replace
Replace
every sequence that matches the pattern with the replacement string.
package com.minte9.basics.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Replace {
public static void main(String[] args) {
Pattern p = Pattern.compile("abc.*? ");
Matcher m = p.matcher("abc abcd bcd cef");
while(m.find()) {
String r = m.replaceAll("AAA ");
System.out.println(r);
}
}
}
Split
Get the text found
on either side of the pattern.
package com.minte9.basics.regexp;
import java.util.regex.Pattern;
public class Split {
public static void main(String[] args) {
String[] words;
Pattern p = Pattern.compile("[ ,.!]");
words = p.split("one two,alpha9 12!done.");
for (String w:words) {
System.out.println(w);
}
words = "AbCdEf".split("(?=[A-Z])");
for(String w:words) {
System.out.println(w);
}
}
}
Lookaround
Lookarounds are
not included in the match.
T
package com.minte9.basics.regexp;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class LookaroundTest {
public static boolean find(String regex, String str) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
return m.find();
}
@Test public void lookBehind() {
assertTrue(find("(?<=a)x", "axyz"));
assertFalse(find("(?<=b)x", "axyz"));
}
@Test public void lookAhead() {
assertTrue(find("(?=x)xyz", "axyz"));
assertFalse(find("(?=x)ax", "axyz"));
}
@Test public void lookBehindNegative() {
assertFalse(find("(!?<=a)x", "ax"));
}
@Test public void lookAheadNegative() {
assertFalse(find("(?!x)x", "ax"));
}
}