Regular Expression Basics

Updated: Sep 21, 2026

An Introduction

I've never quite wrapped by head around what "Regular Expressions" means in terms of the origins or why we call them "Regular Expressions". There doesn't seem to be anything "regular" about them, they seem very "irregular" to me. I don't express myself this way. That is unless I am expressing myself to a computer. As I understand it, it comes from a mathematician's attempt to create patterns calling them "regular expressions". Without a better name or term, it just kind of stuck.

So, what are "Regular Expressions" or as we call them RegEx? A regular expression is a way to do pattern mathing in a file or in code.

A lot of what we have computers do is pattern matching. In fact, the word grep (a tool we use in computers) comes from the abbreviated and repeated use of "Global Regular Expression Print" that comes in the command switches g/re/p. This is from a time in computers when there was no screen to see and if you wanted to see the output you needed to send it to a printer.

But, Regular expressions aren't limited to grep. They are used in the text editors ed, ex, and vi the stream editor sed, and nearly every programming langauge created in the last 50 years.

The Cast of Characters

Most of the characters on your keyboard are treated literally. They include a through z both upper and lowercase as well as the numerals 0 through 9. However, some characters or key sequences have special meaning. They are:

  • ^ - Beginning of line
  • $ - End of Line
  • . - Match any single character
  • * - Match zero or more characters
  • + - Match one or more characters
  • ? - Match zero or one character

  • [...] - Match a group or range of characters
  • Examples

  • [a-z] - Match any Lowercase character a through z
  • [A-Z] - Match any Uppercase character A through Z
  • [0-9] - Macth any numeral 0 through 9
  • [ae] - match an a or an e

  • \ - "escape" to give a special character a literal meaning or give special meaning to an otherwise literal character
  • Examples

  • \\ - Match a literal \
  • \^ - Match a literal ^
  • \$ - Match a literal $
  • \. - Match a literal .
  • \t - Match the Tab character
  • \n - Match a New Line
  • \r - Match a Carriage Return
  • \s - Match any whitespace space, Tab, etc.

A Few Examples of How I Use Regular Expressions everyday

In the vi Editor

Search for all repeating whitespace and replace them with a single space globally

 
:%s:\s\+: :g
 

Add the word send after every new line globally in the file

 
:%s:$:\rsend\r:g
 

Using grep

Find every line that begins with the word zone or Zone

 
grep "^[zZ]one" filename.txt
 

Using tr

Make all characters lowercase

 
cat filename.txt | tr '[A-Z]' '[a-z]'