Skip to content

Programming by Design

If you're not prepared to be wrong, you'll never come up with anything original. – Sir Ken Robinson

  • About
  • Java-PbD
  • C-PbD
  • ASM-PbD
  • Algorithms
  • Other

An Introduction to Regular Expressions

Posted on October 27, 2021January 23, 2023 By William Jojo
Docs

(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}$

Post navigation

❮ Previous Post: Signal Handling
Next Post: Project 6 Hashing Stuff ❯

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright © 2018 – 2025 Programming by Design.