The Python Re Plus (+) Symbol in Regular Expressions

This article is all about the plus “+” symbol in Python’s re library. Study it carefully and master this important piece of knowledge once and for all!

You can also watch the article video while you read over the explanations:

Related article: Python Regex Superpower – The Ultimate Guide

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

What’s the Python Re Plus + Quantifier?

Say, you have any regular expression A. The regular expression (regex) A+ then matches one or more occurrences of A. We call the “+” symbol the at-least-once quantifier because it requires at least one occurrence of the preceding regex. For example, the regular expression ‘yes+’ matches strings ‘yes’, ‘yess’, and ‘yesssssss’. But it does neither match the string ‘ye’, nor the empty string because the plus quantifier + does not apply to the whole regex ‘yes’ but only to the preceding regex ‘s’.

Let’s study some examples to help you gain a deeper understanding.

>>> import re
>>> re.findall('a+b', 'aaaaaab')
['aaaaaab']
>>> re.findall('ab+', 'aaaaaabb')
['abb']
>>> re.findall('ab+', 'aaaaaabbbbb')
['abbbbb']
>>> re.findall('ab+?', 'aaaaaabbbbb')
['ab']
>>> re.findall('ab+', 'aaaaaa')
[]
>>> re.findall('[a-z]+', 'hello world')
['hello', 'world']

Next, we’ll explain those examples one by one.

Examples

You can test your understanding in this interactive Python shell:

Exercise: Guess the output of each of those print() statements and compare it to the actual output. How many did you solve correctly?

Greedy Plus (+) Quantifiers

Here’s the first example:

>>> re.findall('a+b', 'aaaaaab')
['aaaaaab']

You use the re.findall() method. In case you don’t know it, here’s the definition from the Finxter blog article:

The re.findall(pattern, string) method finds all occurrences of the pattern in the string and returns a list of all matching substrings.

Please consult the blog article to learn everything you need to know about this fundamental Python method.

The first argument is the regular expression pattern 'a+b' and the second argument is the string to be searched. In plain English, you want to find all patterns in the string that start with at least one, but possibly many, characters 'a', followed by the character 'b'.

The findall() method returns the matching substring: 'aaaaaab'. The asterisk quantifier + is greedy. This means that it tries to match as many occurrences of the preceding regex as possible. So in our case, it wants to match as many arbitrary characters as possible so that the pattern is still matched. Therefore, the regex engine “consumes” the whole sentence.

The second example is similar:

>>> re.findall('ab+', 'aaaaaabb')
['abb']

You search for the character 'a' followed by at least one character 'b'. As the plus (+) quantifier is greedy, it matches as many 'b's as it can lay its hands on.

Non-Greedy Plus (+) Quantifiers

But what if you want to match at least one occurrence of a regex in a non-greedy manner. In other words, you don’t want the regex engine to consume more and more as long as it can but returns as quickly as it can from the processing.

Again, here’s the example of the greedy match:

>>> re.findall('ab+', 'aaaaaabbbbb')
['abbbbb']

The regex engine starts with the first character 'a' and finds that it’s a partial match. So, it moves on to match the second 'a'—which violates the pattern 'ab+' that allows only for a single character 'a'. So it moves on to the third character, and so on, until it reaches the last character 'a' in the string 'aaaaaabbbbb'. It’s a partial match, so it moves on to the first occurrence of the character 'b'. It realizes that the 'b' character can be matched by the part of the regex 'b+'. Thus, the engine starts matching 'b's. And it greedily matches 'b's until it cannot match any further character. At this point it looks at the result and sees that it has found a matching substring which is the result of the operation.

However, it could have stopped far earlier to produce a non-greedy match after matching the first character 'b'. Here’s an example of the non-greedy quantifier '+?' (both symbols together form one regex expression).

>>> re.findall('ab+?', 'aaaaaabbbbb')
['ab']

Now, the regex engine does not greedily “consume” as many 'b' characters as possible. Instead, it stops as soon as the pattern is matched (non-greedy).

Advanced

For the sake of your thorough understanding, let’s have a look at the other given example:

>>> re.findall('ab+', 'aaaaaa')
[]

You can see that the plus (+) quantifier requires that at least one occurrence of the preceding regex is matched. In the example, it’s the character 'b' that is not partially matched. So, the result is the empty list indicating that no matching substring was found.

Another interesting example is the following:

>>> re.findall('[a-z]+', 'hello world')
['hello', 'world']

You use the plus (+) quantifier in combination with a character class that defines specifically which characters are valid matches.

Note Character Class: Within the character class, you can define character ranges. For example, the character range [a-z] matches one lowercase character in the alphabet while the character range [A-Z] matches one uppercase character in the alphabet.

The empty space is not part of the given character class [a-z], so it won’t be matched in the text. Thus, the result is the list of words that start with at least one character: 'hello', 'world'.

How to Match the Plus (+) Symbol Itself?

You know that the plus quantifier matches at least one of the preceding regular expression. But what if you search for the plus (+) symbol itself? How can you search for it in a string?

The answer is simple: escape the plus symbol in your regular expression using the backslash. In particular, use '\+' instead of '+'. Here’s an example:

>>> import re
>>> text = '2 + 2 = 4'
>>> re.findall(' + ', text)
[]
>>> re.findall(' \+ ', text)
[' + ']
>>> re.findall(' \++ ', '2 ++++ 2 = 4')
[' ++++ ']

If you want to find the '+' symbol in your string, you need to escape it by using the backslash. If you don’t do this, the Python regex engine will interpret it as a normal “at-least-once” regex. Of course, you can combine the escaped plus symbol '\+' with the “at-least-once” regex searching for at least one occurrences of the plus symbol.

Python Regex More Than One Space

Problem: How to match more than one space in a regular expression?

Example: Say, you want to match the following patterns of one ' ', two ' ', and three ' ' spaces.

The plus quantifier A+ matches more than one occurrences of the preceding pattern A. If you want to match more than one whitespace, use the plus quantifier on the whitespace character ' +'. Here’s a practical example:

import re
text = ' hello  world,   Python!'
print(re.findall(' +', text))

The output is the list of all matches of more than one space characters:

# [' ', '  ', '   ']

[Collection] What Are The Different Python Re Quantifiers?

The plus quantifier—Python re +—is only one of many regex operators. If you want to use (and understand) regular expressions in practice, you’ll need to know all of them by heart!

So let’s dive into the other operators:

A regular expression is a decades-old concept in computer science. Invented in the 1950s by famous mathematician Stephen Cole Kleene, the decades of evolution brought a huge variety of operations. Collecting all operations and writing up a comprehensive list would result in a very thick and unreadable book by itself.

Fortunately, you don’t have to learn all regular expressions before you can start using them in your practical code projects. Next, you’ll get a quick and dirty overview of the most important regex operations and how to use them in Python.

Here are the most important regex quantifiers:

QuantifierDescriptionExample
.The wild-card (‘dot’) matches any character in a string except the newline character ‘n’.Regex ‘…’ matches all words with three characters such as ‘abc’, ‘cat’, and ‘dog’.
*The zero-or-more asterisk matches an arbitrary number of occurrences (including zero occurrences) of the immediately preceding regex.Regex ‘cat*’ matches the strings ‘ca’, ‘cat’, ‘catt’, ‘cattt’, and ‘catttttttt’.
?The zero-or-one matches (as the name suggests) either zero or one occurrences of the immediately preceding regex.Regex ‘cat?’ matches both strings ‘ca’ and ‘cat’ — but not ‘catt’, ‘cattt’, and ‘catttttttt’.
+The at-least-one matches one or more occurrences of the immediately preceding regex.Regex ‘cat+’ does not match the string ‘ca’ but matches all strings with at least one trailing character ‘t’ such as ‘cat’, ‘catt’, and ‘cattt’.
^The start-of-string matches the beginning of a string.Regex ‘^p’ matches the strings ‘python’ and ‘programming’ but not ‘lisp’ and ‘spying’ where the character ‘p’ does not occur at the start of the string.
$The end-of-string matches the end of a string.Regex ‘py$’ would match the strings ‘main.py’ and ‘pypy’ but not the strings ‘python’ and ‘pypi’.
A|BThe OR matches either the regex A or the regex B. Note that the intuition is quite different from the standard interpretation of the or operator that can also satisfy both conditions.Regex ‘(hello)|(hi)’ matches strings ‘hello world’ and ‘hi python’. It wouldn’t make sense to try to match both of them at the same time.
AB The AND matches first the regex A and second the regex B, in this sequence.We’ve already seen it trivially in the regex ‘ca’ that matches first regex ‘c’ and second regex ‘a’.

Note that I gave the above operators some more meaningful names (in bold) so that you can immediately grasp the purpose of each regex. For example, the ‘^’ operator is usually denoted as the ‘caret’ operator. Those names are not descriptive so I came up with more kindergarten-like words such as the “start-of-string” operator.

We’ve already seen many examples but let’s dive into even more!

import re

text = '''
    Ha! let me see her: out, alas! he's cold:
    Her blood is settled, and her joints are stiff;
    Life and these lips have long been separated:
    Death lies on her like an untimely frost
    Upon the sweetest flower of all the field.
'''

print(re.findall('.a!', text))
'''
Finds all occurrences of an arbitrary character that is
followed by the character sequence 'a!'.
['Ha!']
'''

print(re.findall('is.*and', text))
'''
Finds all occurrences of the word 'is',
followed by an arbitrary number of characters
and the word 'and'.
['is settled, and']
'''

print(re.findall('her:?', text))
'''
Finds all occurrences of the word 'her',
followed by zero or one occurrences of the colon ':'.
['her:', 'her', 'her']
'''

print(re.findall('her:+', text))
'''
Finds all occurrences of the word 'her',
followed by one or more occurrences of the colon ':'.
['her:']
'''


print(re.findall('^Ha.*', text))
'''
Finds all occurrences where the string starts with
the character sequence 'Ha', followed by an arbitrary
number of characters except for the new-line character. 
Can you figure out why Python doesn't find any?
[]
'''

print(re.findall('n$', text))
'''
Finds all occurrences where the new-line character 'n'
occurs at the end of the string.
['n']
'''

print(re.findall('(Life|Death)', text))
'''
Finds all occurrences of either the word 'Life' or the
word 'Death'.
['Life', 'Death']
'''

In these examples, you’ve already seen the special symbol '\n' which denotes the new-line character in Python (and most other languages). There are many special characters, specifically designed for regular expressions. Next, we’ll discover the most important special symbols.

What’s the Difference Between Python Re + and ? Quantifiers?

You can read the Python Re A? quantifier as zero-or-one regex: the preceding regex A is matched either zero times or exactly once. But it’s not matched more often.

Analogously, you can read the Python Re A+ operator as the at-least-once regex: the preceding regex A is matched an arbitrary number of times but at least once (as the name suggests).

Here’s an example that shows the difference:

>>> import re
>>> re.findall('ab?', 'abbbbbbb')
['ab']
>>> re.findall('ab+', 'abbbbbbb')
['abbbbbbb']

The regex 'ab?' matches the character 'a' in the string, followed by character 'b' if it exists (which it does in the code).

The regex 'ab+' matches the character 'a' in the string, followed by as many characters 'b' as possible (and at least one).

What’s the Difference Between Python Re * and + Quantifiers?

You can read the Python Re A* quantifier as zero-or-more regex: the preceding regex A is matched an arbitrary number of times.

Analogously, you can read the Python Re A+ operator as the at-least-once regex: the preceding regex A is matched an arbitrary number of times too—but at least once.

Here’s an example that shows the difference:

>>> import re
>>> re.findall('ab*', 'aaaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> re.findall('ab+', 'aaaaaaaa')
[]

The regex 'ab*' matches the character 'a' in the string, followed by an arbitary number of occurrences of character 'b'. The substring 'a' perfectly matches this formulation. Therefore, you find that the regex matches eight times in the string.

The regex 'ab+' matches the character 'a', followed by as many characters 'b' as possible—but at least one. However, the character 'b' does not exist so there’s no match.

What are Python Re *?, +?, ?? Quantifiers?

You’ve learned about the three quantifiers:

  • The quantifier A* matches an arbitrary number of patterns A.
  • The quantifier A+ matches at least one pattern A.
  • The quantifier A? matches zero-or-one pattern A.

Those three are all greedy: they match as many occurrences of the pattern as possible. Here’s an example that shows their greediness:

>>> import re
>>> re.findall('a*', 'aaaaaaa')
['aaaaaaa', '']
>>> re.findall('a+', 'aaaaaaa')
['aaaaaaa']
>>> re.findall('a?', 'aaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a', '']

The code shows that all three quantifiers *, +, and ? match as many 'a' characters as possible.

So, the logical question is: how to match as few as possible? We call this non-greedy matching. You can append the question mark after the respective quantifiers to tell the regex engine that you intend to match as few patterns as possible: *?, +?, and ??.

Here’s the same example but with the non-greedy quantifiers:

>>> import re
>>> re.findall('a*?', 'aaaaaaa')
['', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '']
>>> re.findall('a+?', 'aaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> re.findall('a??', 'aaaaaaa')
['', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '']

In this case, the code shows that all three quantifiers *?, +?, and ?? match as few ‘a’ characters as possible.

Related Re Methods

There are five important regular expression methods which you should master:

  • The re.findall(pattern, string) method returns a list of string matches. Read more in our blog tutorial.
  • The re.search(pattern, string) method returns a match object of the first match. Read more in our blog tutorial.
  • The re.match(pattern, string) method returns a match object if the regex matches at the beginning of the string. Read more in our blog tutorial.
  • The re.fullmatch(pattern, string) method returns a match object if the regex matches the whole string. Read more in our blog tutorial.
  • The re.compile(pattern) method prepares the regular expression pattern—and returns a regex object which you can use multiple times in your code. Read more in our blog tutorial.
  • The re.split(pattern, string) method returns a list of strings by matching all occurrences of the pattern in the string and dividing the string along those. Read more in our blog tutorial.
  • The re.sub(The re.sub(pattern, repl, string, count=0, flags=0) method returns a new string where all occurrences of the pattern in the old string are replaced by repl. Read more in our blog tutorial.

These seven methods are 80% of what you need to know to get started with Python’s regular expression functionality.

Where to Go From Here?

You’ve learned everything you need to know about the asterisk quantifier * in this regex tutorial.

Summary: Regex A+ matches one or more occurrences of regex A. The “+” symbol is the at-least-once quantifier because it requires at least one occurrence of the preceding regex. The non-greedy version of the at-least-once quantifier is A+? with the trailing question mark.

Want to earn money while you learn Python? Average Python programmers earn more than $50 per hour. You can certainly become average, can’t you?

Join the free webinar that shows you how to become a thriving coding business owner online!

[Webinar] Are You a Six-Figure Freelance Developer?

Join us. It’s fun! 🙂