Skip to content

Instantly share code, notes, and snippets.

@Bauepete
Created Apr 8, 2019
Embed
What would you like to do?
RegEx handling in Java and the most important RegEx Patterns
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println("RegEx Demo");
// The general java approach: Pattern, Matcher
Pattern p = Pattern.compile("b(a|e)uer");
Matcher m = p.matcher("bauer beuer");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println(m.find());
// System.out.println(m.start());
// System.out.println(m.group());
// Character classes
System.out.println("\nCharacter Classes");
p = Pattern.compile("b[ae]uer"); // same meaning as above
m = p.matcher("bauer beuer");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println("\nSimple identifier");
p = Pattern.compile("^[A-Za-z][A-Za-z0-9]*$");
m = p.matcher("127asfd");
System.out.println(m.find());
// System.out.println(m.start());
// System.out.println(m.group());
System.out.println("\nOptional Symbols");
p = Pattern.compile("Ba(ue)?r");
m = p.matcher("Bauer");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println("\nMultiple occurrences");
p = Pattern.compile("Baue+r");
m = p.matcher("Baueeeeeeeeeeer");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
p = Pattern.compile("Baue{1,3}r");
m = p.matcher("Bauer");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
System.out.println("\nPredefined char classes");
p = Pattern.compile("Bau.r");
m = p.matcher("Bau!r");
System.out.println(m.find());
System.out.println(m.start());
System.out.println(m.group());
// [0-9] == (\d)
// \D not \d
// white space (blank, tab, newline): \s
// \S not \s
// cheat sheet: https://www.petefreitag.com/cheatsheets/regex/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment