I’m taking Theory of Computation (text by Sudkamp) this semester and one of the immediate benefits is being able to understand & interpret regular expressions. java.util.regex is a package that contains “classes (Pattern and Matcher) for matching character sequences against patterns specified by regular expressions.”
From the API specifications, here’s how you use the Pattern class:
Pattern p = Pattern.compile(“a*b”); //Matches just 1 “b” as well as *any* number of “a”s before that one b. Creating a Pattern like this allows you to reuse this object.
Matcher m = p.matcher(“aaaaab”); //Matches what’s in the parentheses against the Pattern object referenced by p.
boolean b = m.matches(); //Returns true if the user’s input matched the pattern.
If you only want to match just once or twice, you can use an expression like this (which evaluates to True or False).
Pattern.matches(“a*b”,”aaaaab”) –> In this case, “aaaaab” fits the pattern so it will return true.
There are several websites you can test out any regex expression you have in mind e.g. rubular.com, RegExr, etc.
This has actually come in handy for my first project of the semester in my Java class. Our task is to create a Hanging With Friends/Hangman cheater of sorts. A sample run of the program should look like this:
jane@Jumanji:~$ java Hangman "??arm" "c"Here are all of the possible words:inarmswarmtharmunarmh: 1i: 1n: 2s: 1t: 1u: 1w: 1Your best guess is: 'n.'
jane@Jumanji:~$ java Hangman "??art" "MEHY"Here are all of the possible words:boartquartscartswartb: 1c: 1o: 1q: 1s: 2u: 1w: 1Your best guess is: 's.'
The syntax is: java Hangman param1 param2.
Parameter 1 – is a string that should only contain question marks and/or letters. This is a mandatory argument that must be present before the program can proceed. Word matching will be done based on Parameter 1. However, Parameter 2 is an optional argument which allows the user to specify characters that are definitely NOT in this list of matched words. The plot thickens. 🙂
In any case, I have a version 1 of this program running with the necessary checks & balances. I made extensive use of helper methods and it’s not very efficient but that’s why I tried to have it running so I could step back and ‘refine’ as best as I can.
Minor edit: updated my code to remove a bug where characters already guessed were showing up. Cheers!
Buggy output jane@Jumanji:~$ java Hangman ??art SHapart --> should not be there because A was already guessed.boartlyartpeartquarta: 1b: 1e: 1l: 1o: 1p: 2q: 1u: 1y: 1Your best guess is: 'p.'