Created
April 8, 2019 12:15
-
-
Save bauepete/eb6d33e75464bfdf3e6bdf0c2916d6e6 to your computer and use it in GitHub Desktop.
RegEx handling in Java and the most important RegEx Patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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