This is a continuation of Part 1, and now we’ll memorize the wild cards and repetitions in regular expressions.
So, we’ll just go through the line of expressions with a way to memorize each:
. – A period matches any character. Visualize a million grains of sand. Each of them is the same and matches the other exactly.
\w – Backslash w matches any alphanumeric character and “_”. Think of a wireless area network. It’s all lowercase, and and it can only use alphanumeric characters in the name.
\W – Backslash capital W matches any non-alphanumeric character. Think of George W Bush. He’s everything but any alphanumeric character. Nothing but wild cards, and there’s a capital W in his middle name.
\s – Backlash s matches a whitespace character. There’s plenty of space in outer space. Both lower case.
\S – Matches any non-whitespace character. Imagine a bunch of big S’s cramped into a small room. No space.
\d – Matches any digit character. Imagine a geeky little d who loves digits.
\D – Matches any non-digit character. Imagine a giant D bully that picks on anyone who’s a digit.
\t – Matches a tab. Shouldn’t you drink tea instead of Tab (A soft drink)?
\n – Matches a newline. Imagine an n going down a zip-line in New Guinea.
\r – Matches a return. Imagine an r on it’s way home from a long journey.
You follow any of these up with a wild card:
* – Matches a character 0 or more times. Imagine a star who’s died any become a black hole. It accepts anything.
+ – Matches a character 1 or more times. In order to add, you have to have at least 1.
? – Matches 1 or 0 times. Think of “To be or not to be?” There are to options. 1 or 0.
{n} – Matches n times. Imagine n n’s are trapped in n cages.
{n,} – Matches at least n times. Imagine n, and at least one other person trapped in cages.
{n,m} – Matches at least n times, but no more than m. N can break out until he reaches m’s cage.
So, for example:
$strung =~ m/S\{5}\/; # 5 non-whitespace characters?
$strang =~ m/\n{2}\/; # 2 newlines in a row?
See, using regular expressions is easy! It just looks difficult because you didn’t take the time to visualize easy ways to remember them. Write down the ways of memorization for yourself, and really visualize each of the above. You can really memorize all of the regular expressions in under 20 minutes when you’re focused.