Regular Expressions
Last updated on 2025-12-12 | Edit this page
Overview
Questions
- How can you imagine using regular expressions in your work?
Objectives
- Identify potential use cases for regular expressions
- Recognize common regex metacharacters
- Use regular expressions in searches
Regular expressions
Regular expressions are a concept and an implementation used in many different programming environments for sophisticated pattern matching. They are an incredibly powerful tool that can amplify your capacity to find, manage, and transform data and files.
A regular expression, often abbreviated to regex, is a method of using a sequence of characters to define a search to match strings, i.e. “find and replace”-like operations. In computation, a ‘string’ is a contiguous sequence of symbols or values. For example, a word, a date, a set of numbers (e.g., a phone number), or an alphanumeric value (e.g., an identifier). A string could be any length, ranging from empty (zero characters) to one that spans many lines of text (including line break characters). The terms ‘string’ and ‘line’ are sometimes used interchangeably, even when they are not strictly the same thing.
In library searches, we are most familiar with a small part of regular expressions known as the “wild card character,” but there are many more features to the complete regular expressions syntax. Regular expressions will let you:
- Match on types of characters (e.g. ‘upper case letters’, ‘digits’, ‘spaces’, etc.).
- Match patterns that repeat any number of times.
- Capture the parts of the original string that match your pattern.
Regex can also be useful for daily work. For example, say your organization wants to change the way they display telephone numbers on their website by removing the parentheses around the area code. Rather than search for each specific phone number (that could take forever and be prone to error) or searching for every open parenthesis character (could also take forever and return many false-positives), you could search for the pattern of a phone number. Regular expressions rely on the use of literal characters and metacharacters. A metacharacter is any American Standard Code for Information Interchange (ASCII) character that has a special meaning. By using metacharacters and possibly literal characters, you can construct a regex for finding strings or files that match a pattern rather than a specific string.
Since regular expressions defines some ASCII characters as
“metacharacters” that have more than their literal meaning, it is also
important to be able to “escape” these metacharacters to use them for
their normal, literal meaning. For example, the period .
means “match any character”, but if you want to match a period then you
will need to use a \ in front of it to signal to the
regular expression processor that you want to use the period as a plain
old period and not a metacharacter. That notation is called “escaping”
the special character. The concept of “escaping” special characters is
shared across a variety of computational settings, including markdown
and Hypertext Markup Language (HTML).
Regex Syntax and interoperability
Most regular expression implementations employ similar syntaxes and metacharacters (generally influenced by the regex syntax of a programming language called Perl), and they behave similarly for most pattern-matching in this lesson. But there are differences, often subtle, in each, so it’s always a good practice to read the application or language’s documentation whenever available, especially when you start using more advanced regex features. Some programs, notably many UNIX command line programs (for more on UNIX see our ‘Shell Lesson’), use an older regex standard (called ‘POSIX regular expressions’) which is less feature-rich and uses different metacharacters than Perl-influenced implementations. For the purposes of our lesson, you do not need to worry too much about all this, but if you want to follow up on this see this detailed syntax comparison.
A very simple use of a regular expression would be to locate the same
word spelled two different ways. For example the regular expression
organi[sz]e matches both organise and
organize. But because it locates all matches for the
pattern in the file, not just for that word, it would also match
reorganise, reorganize,
organises, organizes, organised,
organized, etc.
Learning common regex metacharacters
Square brackets can be used to define a list or range of characters to be found. So:
-
[ABC]matches A or B or C. -
[A-Z]matches any upper case letter. -
[A-Za-z]matches any upper or lower case letter. -
[A-Za-z0-9]matches any upper or lower case letter or any digit.
Then there are:
-
.matches any character. -
\dmatches any single digit. -
\wmatches any part of word character (equivalent to[A-Za-z0-9]). -
\smatches any space, tab, or newline. -
\used to escape the following character when that character is a special character. So, for example, a regular expression that found.comwould be\.combecause.is a special character that matches any character. -
^is an “anchor” which asserts the position at the start of the line. So what you put after the caret will only match if they are the first characters of a line. The caret is also known as a circumflex. -
$is an “anchor” which asserts the position at the end of the line. So what you put before it will only match if they are the last characters of a line. -
\basserts that the pattern must match at a word boundary. Putting this either side of a word stops the regular expression matching longer variants of words. So:- the regular expression
markwill match not onlymarkbut also findmarking,market,unremarkable, and so on. - the regular expression
\bwordwill matchword,wordless, andwordlessly. - the regular expression
comb\bwill matchcombandhoneycombbut notcombine. - the regular expression
\brespect\bwill matchrespectbut notrespectableordisrespectful.
- the regular expression
So, what is ^[Oo]rgani.e\b going to match?
Using special characters in regular expression matches
What will the regular expression ^[Oo]rgani.e\b
match?
organise
organize
Organise
Organize
organife
Organike
Or, any other string that starts a line, begins with a letter
o in lower or capital case, proceeds with
rgani, has any character in the 7th position, and ends with
the letter e. See solution
visualised on Regexper.com
Getting help with regular expressions
Although powerful, the mix of special and regular characters in a regular expression can make them difficult to interpret and to troubleshoot when we get them wrong. The Regexper tool linked in the solution above visualises and annotates a regular expression provided by the user, which can be very helpful as you learn to read and write them. Other online tools such as Regex101 provide a more powerful – and more complex! – interface that can help you develop a regular expression to fit your use case.
If you get stuck when writing a regular expression, it is helpful to prepare a collection of “test strings”: words, sentences, or other blocks of text that represent the things you do and do not want to match. To test for matches you do not want, think about words/sentences/text that is similar to the matches you do want to make, and include those in your test strings. For example, you might include “disorganised” in a set of test strings for the regular expression in the exercise above, if you only wanted to match whole words.
Paste your test strings into a new file in your favourite text editor or the Test String box on Regex101 then paste or compose your regular expression to see which of these test strings are matched.
As well as trying to figure things out on your own, you might also get help by talking to somebody! If you have a colleague or friend with more expertise in regular expressions than you have, show them the problem you are having and ask them for help. Sometimes, the act of articulating your question can help you to identify what is going wrong. This is known as “rubber duck debugging” among programmers.
Generative AI
It is increasingly common for people to use generative AI chatbots such as ChatGPT to get help with regular expressions. You will probably receive some useful guidance by presenting your regular expression to the chatbot and asking why it matches (or does not match) a given string. However, the way this help is provided by the chatbot is different from that provided by a human. Generative AI chatbots, which are based on an advanced statistical model, respond by generating the most likely sequence of text that would follow the prompt they are given.
While responses from generative AI tools can often be helpful, they are not always reliable. These tools sometimes generate plausible but incorrect or misleading information, so (just as with an answer found on the internet or shared with you by somebody else) it is essential to verify their accuracy. You need the knowledge and skills to be able to understand these responses, to judge whether or not they are accurate, and to fix any errors in the regular expression the chatbot offers you.
In addition to asking for help, generative AI tools can be used to generate regular expressions from scratch (especially when given clear and precise instructions and examples); extend, improve and reorganise existing regular expressions; and more. However, there are drawbacks that you should be aware of.
The models used by these tools have been “trained” on very large volumes of data, much of it taken from the internet, and the responses they produce reflect that training data, and may recapitulate its inaccuracies or biases. The environmental costs (energy and water use) of LLMs are a lot higher than other technologies, both during development (known as training) and when an individual user uses one (also called inference). For more information see the AI Environmental Impact Primer developed by researchers at HuggingFace, an AI hosting platform. Concerns also exist about the way the data for this training was obtained, with questions raised about whether the people developing the LLMs had permission to use it. Other ethical concerns have also been raised, such as reports that workers were exploited during the training process.
We recommend that you avoid getting help from generative AI during the workshop because the foundational knowledge and skills you will learn in this lesson by writing and fixing your own regular expressions are essential to be able to evaluate the correctness and safety of any answers you receive from other people or a generative AI chatbot. If you choose to use these tools in the future, the expertise you gain from learning and practising these fundamentals on your own will help you use them more effectively.
More special characters
Other useful special characters are:
-
*matches the preceding element zero or more times. For example, ab*c matches “ac”, “abc”, “abbbc”, etc. -
+matches the preceding element one or more times. For example, ab+c matches “abc”, “abbbc” but not “ac”. -
?matches when the preceding character appears zero or one time. -
{VALUE}matches the preceding character the number of times defined by VALUE; ranges, say, 1-6, can be specified with the syntax{VALUE,VALUE}, e.g.\d{1,9}will match any number between one and nine digits in length. -
|means or. -
/irenders an expression case-insensitive (equivalent to[A-Za-z]).
So, what are these going to match?
^[Oo]rgani.e\w*
What will the regular expression ^[Oo]rgani.e\w*
match?
organise
Organize
organifer
Organi2ed111
Or, any other string that starts a line, begins with a letter
o in lower or capital case, proceeds with
rgani, has any character in the 7th position, follows with
letter e and zero or more characters from the range
[A-Za-z0-9].
[Oo]rgani.e\w+$
What will the regular expression [Oo]rgani.e\w+$
match?
organiser
Organized
organifer
Organi2ed111
Or, any other string that ends a line, begins with a letter
o in lower or capital case, proceeds with
rgani, has any character in the 7th position, follows with
letter e and at least one or more
characters from the range [A-Za-z0-9].
^[Oo]rgani.e\w?\b
What will the regular expression ^[Oo]rgani.e\w?\b
match?
organise
Organized
organifer
Organi2ek
Or, any other string that starts a line, begins with a letter
o in lower or capital case, proceeds with
rgani, has any character in the 7th position, follows with
letter e, and ends with zero or one
characters from the range [A-Za-z0-9].
^[Oo]rgani.e\w?$
What will the regular expression ^[Oo]rgani.e\w?$
match?
organise
Organized
organifer
Organi2ek
Or, any other string that starts and ends a line, begins with a
letter o in lower or capital case, proceeds with
rgani, has any character in the 7th position, follows with
letter e and zero or one characters from
the range [A-Za-z0-9].
\b[Oo]rgani.e\w{2}\b
What will the regular expression \b[Oo]rgani.e\w{2}\b
match?
organisers
Organizers
organifers
Organi2ek1
Or, any other string that begins with a letter o in
lower or capital case after a word boundary, proceeds with
rgani, has any character in the 7th position, follows with
letter e, and ends with two characters
from the range [A-Za-z0-9].
\b[Oo]rgani.e\b|\b[Oo]rgani.e\w{1}\b
What will the regular expression
\b[Oo]rgani.e\b|\b[Oo]rgani.e\w{1}\b match?
organise
Organi1e
Organizer
organifed
Or, any other string that begins with a letter o in
lower or capital case after a word boundary, proceeds with
rgani, has any character in the 7th position, and end with
letter e, or any other string that begins with a letter
o in lower or capital case after a word boundary, proceeds
with rgani, has any character in the 7th position, follows
with letter e, and ends with a single character from the
range [A-Za-z0-9].
This logic is useful when you have lots of files in a directory, when those files have logical file names, and when you want to isolate a selection of files. It can be used for looking at cells in spreadsheets for certain values, or for extracting some data from a column of a spreadsheet to make new columns. There are many other contexts in which regex is useful when using a computer to search through a document, spreadsheet, or file structure. Some real-world use cases for regex were included on a ACRL Tech Connect blog post now archived at Library Hat .
To embed this knowledge we will not - however - be using computers. Instead we’ll use pen and paper for now.
Exercise
Work in teams of four to six on the exercises below. When you think you have the right answer, check it against the solution.
When you finish, split your team into two groups and write each other some tests. These should include a) strings you want the other team to write regex for and b) regular expressions you want the other team to work out what they would match.
Then test each other on the answers. If you want to check your logic use regex101, myregexp, regex pal or regexper.com: the first three help you see what text your regular expression will match, the latter visualises the workflow of a regular expression.
Using square brackets
What will the regular expression Fr[ea]nc[eh] match?
French
France
Frence
Franch
Note that the way this regular expression is constructed, it will
match misspellings such as Franch and Frence.
Lacking an “anchor” such as ^ or \b, this will
also find strings where there are characters to either side of the
regular expression, such as in French,
France's, French-fried.
Using dollar signs
What will the regular expression Fr[ea]nc[eh]$
match?
French
France
Frence
Franch
This will match the pattern only when it appears at the end of a
line. It will also find strings with other characters coming
before the pattern, for example, in French or
faux-French.
Introducing options
What would match the strings French and
France that appear at the beginning of a line?
^France|^French
This will also find words where there were characters after
French such as Frenchness.
Case insensitivity
How do you match the whole words colour and
color (case insensitive)?
\b[Cc]olou?r\b|\bCOLOU?R\b
/colou?r/i
In real life, you should only come across the case
insensitive variations colour, color,
Colour, Color, COLOUR, and
COLOR (rather than, say, coLour). So based on
what we know, the logical regular expression is
\b[Cc]olou?r\b|\bCOLOU?R\b.
An alternative more elegant option we’ve not discussed is to take
advantage of the / delimiters and add an ‘ignore case’
flag. To use these flags, include / delimiters before and
after the expression then letters after to raise each flag (where
i is ‘ignore case’): so /colou?r/i will match
all case insensitive variants of colour and
color.
Word boundaries
How would you find the whole word headrest and or
head rest but not head rest (that is, with
two spaces between head and rest?
\bhead ?rest\b
Note that although \bhead\s?rest\b does work, it will
also match zero or one tabs or newline characters between
head and rest. So again, although in most real
world cases it will be fine, it isn’t strictly correct.
Matching non-linguistic patterns
How would you find a string that ends with four letters preceded by at least one zero?
0+[A-Za-z]{4}\b
Matching digits
How do you match any four-digit string anywhere?
\d{4}
Note: this will also match four-digit strings within longer strings of numbers and letters.
Matching dates
How would you match the date format dd-MM-yyyy?
\b\d{2}-\d{2}-\d{4}\b
Depending on your data, you may choose to remove the word bounding.
Matching multiple date formats
How would you match the date format dd-MM-yyyy or
dd-MM-yy at the end of a line only?
\d{2}-\d{2}-\d{2,4}$
Note this will also find strings such as 31-01-198 at
the end of a line, so you may wish to check your data and revise the
expression to exclude false positives. Depending on your data, you may
choose to add word bounding at the start of the expression.
Matching publication formats
How would you match publication formats such as
British Library : London, 2015 and
Manchester University Press: Manchester, 1999?
.* ?: .*, \d{4}
Without word boundaries you will find that this matches any text you
put before British or Manchester.
Nevertheless, the regular expression does a good job on the first look
up and may be need to be refined on a second, depending on your
data.
- Regular expressions are a language for pattern matching.