(Updated October 27, 2021)
Overview
Pattern matching is a frequent requirement in programming. As a result programmers are often tasked with find the best way to prove that a string matches a specific set of criteria: email address format, password requirements, IP address format (IPv4 and IPv6), and the list goes on an on.
The problem that comes about is many of the methods of proving the pattern valid can be incredibly complex to code. This is because the solutions often involve recursion and other tools that may become unwieldy for some programmers who simply need a YES or NO answer.
Regular expressions (sometimes called RE or regex) were created to help solve this problem. Through a relatively simple language, practically any pattern can be tested to see if it matches a predetermined criteria.
How It Works
The easiest way to get started is to use a tool the helps with the creation process. One incredibly powerwul tool is called Regex 101. Once you arrive you cen begin building your own regex and test it.
Some Basics
Generally, we are looking to match text.
Some Additional Patterns
#Good…but…
^[a-zA-Z_][a-z^A-Z_\$0-9]*$
#Better – handles ‘_’ more proficiently
^(_[a-zA-Z0-9_$]+|[a-zA-Z][a-z^A-Z_\$0-9]*)$
#Integer
^[-+]?[0-9]+$
#Floats
^([0-9]+\.|[0-9]*\.[0-9]+)$
#scientific notation
^([0-9]*\.[0-9]+([eE][+-]?[0-9]+)?)$
public\s+class \w+\s*\{\s*public\s+static\s+void\s+main\s*\(\s*String\s*\[\]\s+args\s*\)\s*\{[\S\s]*\}\s*\}
^(?=[MDCLXVI])C?M*C?D?X?C{0,3}X?L?I?X{0,3}I?V?I{0,3}$
Roman Numerals
^M*(?:CM)?(?:CD|D?(?:C{0,2}XC|C{0,3})?)?(?:XL|L?(?:X{0,2}IX|X{0,3})?)?(?:IV|V?I{0,3})?$
IP address
^(?:0|[1-9][0-9]?|1[0-9]{0,2}|2(?:[0-4][0-9]|5[0-5]))(?:\.(?:0|[1-9][0-9]?|1[0-9]{0,2}|2(?:[0-4][0-9]|5[0-5]))){3}$