Python Regex Fullmatch

Why have regular expressions survived seven decades of technological disruption? Because coders who understand regular expressions have a massive advantage when working with textual data. They can write in a single line of code what takes others dozens!

Python Regex Fullmatch

This article is all about the re.fullmatch(pattern, string) method of Python’s re library. There are three similar methods to help you use regular expressions:

  • The re.findall(pattern, string) method returns a list of string matches. Check out our blog tutorial.
  • The re.search(pattern, string) method returns a match object of the first match. Check out our blog tutorial.
  • The re.match(pattern, string) method returns a match object if the regex matches at the beginning of the string. Check out our blog tutorial.

Related article: Python Regex Superpower – The Ultimate Guide

So how does the re.fullmatch() method work? Let’s study the specification.

Table of Contents

How Does re.fullmatch() Work in Python?

The re.fullmatch(pattern, string) method returns a match object if the pattern matches the whole string. A match object contains useful information such as the matching groups and positions. An optional third argument flags enables customization of the regex engine, for example to ignore capitalization.

Specification:

re.fullmatch(pattern, string, flags=0)

The re.fullmatch() method has up to three arguments.

  • pattern: the regular expression pattern that you want to match.
  • string: the string which you want to search for the pattern.
  • flags (optional argument): a more advanced modifier that allows you to customize the behavior of the function. Want to know how to use those flags? Check out this detailed article on the Finxter blog.

We’ll explore them in more detail later.

Return Value:

The re.fullmatch() method returns a match object. You may ask (and rightly so):

What’s a Match Object?

If a regular expression matches a part of your string, there’s a lot of useful information that comes with it: what’s the exact position of the match? Which regex groups were matched—and where?

The match object is a simple wrapper for this information. Some regex methods of the re package in Python—such as fullmatch()—automatically create a match object upon the first pattern match.


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.


At this point, you don’t need to explore the match object in detail. Just know that we can access the start and end positions of the match in the string by calling the methods m.start() and m.end() on the match object m:

>>> m = re.fullmatch('h...o', 'hello')
>>> m.start()
0
>>> m.end()
5

In the first line, you create a match object m by using the re.fullmatch() method. The pattern 'h...o' matches in the string 'hello' at start position 0 and end position 5. But note that as the fullmatch() method always attempts to match the whole string, the m.start() method will always return zero.

Now, you know the purpose of the match object in Python. Let’s check out a few examples of re.fullmatch()!

A Guided Example for re.fullmatch()

First, you import the re module and create the text string to be searched for the regex patterns:

>>> import re
>>> text = '''
Call me Ishmael. Some years ago--never mind how long precisely
--having little or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail about a little
and see the watery part of the world.
'''

Let’s say you want to match the full text with this regular expression:

>>> re.fullmatch('Call(.|n)*', text)
>>> 

The first argument is the pattern to be found: 'Call(.|n)*'. The second argument is the text to be analyzed. You stored the multi-line string in the variable text—so you take this as the second argument. The third argument flags of the fullmatch() method is optional and we skip it in the code.

There’s no output! This means that the re.fullmatch() method did not return a match object. Why? Because at the beginning of the string, there’s no match for the 'Call' part of the regex. The regex starts with an empty line!

So how can we fix this? Simple, by matching a new line character 'n' at the beginning of the string.

>>> re.fullmatch('nCall(.|n)*', text)
<re.Match object; span=(0, 229), match='nCall me Ishmael. Some years ago--never mind how>

The regex (.|n)* matches an arbitrary number of characters (new line characters or not) after the prefix 'nCall'. This matches the whole text so the result is a match object. Note that there are 229 matching positions so the string included in resulting match object is only the prefix of the whole matching string. This fact is often overlooked by beginner coders.

What’s the Difference Between re.fullmatch() and re.match()?

The methods re.fullmatch() and re.match(pattern, string) both return a match object. Both attempt to match at the beginning of the string. The only difference is that re.fullmatch() also attempts to match the end of the string as well: it wants to match the whole string!

You can see this difference in the following code:

>>> text = 'More with less'
>>> re.match('More', text)
<re.Match object; span=(0, 4), match='More'>
>>> re.fullmatch('More', text)
>>> 

The re.match('More', text) method matches the string 'More' at the beginning of the string 'More with less'. But the re.fullmatch('More', text) method does not match the whole text. Therefore, it returns the None object—nothing is printed to your shell!

What’s the Difference Between re.fullmatch() and re.findall()?

There are two differences between the re.fullmatch(pattern, string) and re.findall(pattern, string) methods:

  • re.fullmatch(pattern, string) returns a match object while re.findall(pattern, string) returns a list of matching strings.
  • re.fullmatch(pattern, string) can only match the whole string, while re.findall(pattern, string) can return multiple matches in the string.

Both can be seen in the following example:

>>> text = 'the 42th truth is 42'
>>> re.fullmatch('.*?42', text)
<re.Match object; span=(0, 20), match='the 42th truth is 42'>
>>> re.findall('.*?42', text)
['the 42', 'th truth is 42']

Note that the regex .*? matches an arbitrary number of characters but it attempts to consume as few characters as possible. This is called “non-greedy” match (the *? operator). The fullmatch() method only returns a match object that matches the whole string. The findall() method returns a list of all occurrences. As the match is non-greedy, it finds two such matches.

What’s the Difference Between re.fullmatch() and re.search()?

The methods re.fullmatch() and re.search(pattern, string) both return a match object. However, re.fullmatch() attempts to match the whole string while re.search() matches anywhere in the string.

You can see this difference in the following code:

>>> text = 'Finxter is fun!'
>>> re.search('Finxter', text)
<re.Match object; span=(0, 7), match='Finxter'>
>>> re.fullmatch('Finxter', text)
>>> 

The re.search() method retrieves the match of the 'Finxter' substring as a match object. But the re.fullmatch() method has no return value because the substring 'Finxter' does not match the whole string 'Finxter is fun!'.

How to Use the Optional Flag Argument?

As you’ve seen in the specification, the fullmatch() method comes with an optional third 'flag' argument:

re.fullmatch(pattern, string, flags=0)

What’s the purpose of the flags argument?

Flags allow you to control the regular expression engine. Because regular expressions are so powerful, they are a useful way of switching on and off certain features (for example, whether to ignore capitalization when matching your regex).

Syntax Meaning
re.ASCII If you don’t use this flag, the special Python regex symbols w, W, b, B, d, D, s and S will match Unicode characters. If you use this flag, those special symbols will match only ASCII characters — as the name suggests.
re.A Same as re.ASCII
re.DEBUG If you use this flag, Python will print some useful information to the shell that helps you debugging your regex.
re.IGNORECASE If you use this flag, the regex engine will perform case-insensitive matching. So, if you’re searching for character class [A-Z], it will also match [a-z].
re.I Same as re.IGNORECASE
re.LOCALE Don’t use this flag — ever. It’s depreciated—the idea was to perform case-insensitive matching depending on your current locale. But it isn’t reliable.
re.L Same as re.LOCALE
re.MULTILINE This flag switches on the following feature: the start-of-the-string regex '^' matches at the beginning of each line (rather than only at the beginning of the string). The same holds for the end-of-the-string regex '$' that now matches also at the end of each line in a multi-line string.
re.M Same as re.MULTILINE
re.DOTALL Without using this flag, the dot regex '.' matches all characters except the newline character 'n'. Switch on this flag to really match all characters including the newline character.
re.S Same as re.DOTALL
re.VERBOSE To improve the readability of complicated regular expressions, you may want to allow comments and (multi-line) formatting of the regex itself. This is possible with this flag: all whitespace characters and lines that start with the character '#' are ignored in the regex.
re.X Same as re.VERBOSE

Here’s how you’d use it in a practical example:

>>> text = 'Python is great!'
>>> re.search('PYTHON', text, flags=re.IGNORECASE)
<re.Match object; span=(0, 6), match='Python'>

Although your regex 'PYTHON' is all-caps, we ignore the capitalization by using the flag re.IGNORECASE.

Related Article: Python Regex Flags [Ultimate Guide]

Regex Methods Overview Video — re.findall() vs. re.search() vs. re.match() vs. re.fullmatch()

Where to Go From Here?

This article has introduced the re.fullmatch(pattern, string) method that attempts to match the whole string—and returns a match object if it succeeds or None if it doesn’t.

Learning Python is hard. But if you cheat, it isn’t as hard as it has to be:

Download 8 Free Python Cheat Sheets now!

Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: The Smartest Way to Learn Python Regex (Amazon Kindle/Print, opens in new tab).

Author: Shantun Parmar

63 thoughts on “Python Regex Fullmatch

  1. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  2. Together with everything that seems to be developing inside this particular subject matter, all your points of view are generally quite stimulating. Nevertheless, I appologize, but I can not give credence to your whole idea, all be it radical none the less. It looks to everyone that your opinions are not totally rationalized and in simple fact you are yourself not totally certain of the argument. In any event I did enjoy examining it. Ernest Loner

  3. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  4. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  5. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  6. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  7. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  8. A lot of thanks for all your valuable efforts on this site. Kate loves getting into investigation and it’s really easy to understand why. I know all concerning the dynamic medium you give informative secrets on this web blog and as well as foster participation from others on that content plus our daughter is always discovering a lot. Have fun with the remaining portion of the new year. You are conducting a great job.

  9. I simply needed to thank you so much once again. I am not sure the things that I would have used without those tricks shown by you relating to this topic. This has been the traumatic situation in my view, nevertheless viewing your well-written way you treated the issue took me to weep with joy. Now i am thankful for your work as well as wish you recognize what an amazing job your are undertaking training the rest with the aid of your websites. Probably you haven’t met any of us.

  10. Its rare for me to discover something on the internet thats as entertaining and intriguing as what youve got here. Your page is lovely, your graphics are outstanding, and whats more, you use reference that are relevant to what you are saying. Youre definitely one in a million, good job!

  11. Ꮋi!, I wаnt to begin offering ѕeveral seo sergices оn а site foг freelancers. I’m currently usіng Fiverr buut they keep on permanently banning mү accounts аnd misappropriating mу money. What alternative reliabpe freelancing sitfes ɑrе thеre? I am alreaɗy verified ᴡith SweatyQuid аnd UpWork and a couplke of ߋthers. Thаnk yоu!

  12. Aw, this was a very nice post. Finding the time and actual effort to generate a great article… but what can I say… I put things off a lot and don’t seem to get nearly anything done.

  13. I think that what you posted was actually very logical.
    But, consider this, suppose you added a little content?
    I am not saying your information isn’t good, but what if you added something that makes people desire more?
    I mean Python Regex Fullmatch – Cooding Dessign is a little boring.
    You might look at Yahoo’s home page and note how they create article
    titles to get people to click. You might add a related video or a picture or two to get people excited about everything’ve got
    to say. In my opinion, it might make your website a little livelier.

  14. Hi!,I love your writing very much! proportion we communicate more about your article on AOL? I require an expert in this area to unravel my problem. Maybe that is you! Taking a look forward to see you.

  15. My spouse and I stumbled over here different web page and thought I might as well check things out.
    I like what I see so now i’m following you. Look forward to looking
    into your web page for a second time.

  16. The new Zune browser is surprisingly good, but not as good as the iPod’s. It works well, but isn’t as fast as Safari, and has a clunkier interface. If you occasionally plan on using the web browser that’s not an issue, but if you’re planning to browse the web alot from your PMP then the iPod’s larger screen and better browser may be important.

  17. What’s Taking place i’m new to this, I stumbled upon this I
    have found It positively useful and it has helped me out loads.
    I hope to give a contribution & assist different customers like its helped me.
    Good job.

  18. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get got an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly very often inside case you shield this increase.

  19. Hello There. I discovered your weblog the usage of msn. This is an extremely neatly written article. I will make sure to bookmark it and return to read more of your helpfulinfo. Thanks for the post. I will certainly comeback.

  20. Wow, wonderful blog format! How long have you been blogging for? you made running a blog glance easy. The entire look of your website is excellent, as well as the content!

  21. Oh my goodness! Awesome article dude! Thank you, However I am experiencing issues with your RSS. I don’t know the reason why I am unable to join it. Is there anybody getting the same RSS issues? Anybody who knows the answer can you kindly respond? Thanks!!

  22. Hi, I do believe this is a great web site. I stumbledupon it 😉 I may return once again since I book-marked it. Money and freedom is the best way to change, may you be rich and continue to help others.

  23. Amazing blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your design. Appreciate it

  24. I had this page bookmarked a while previously but my notebook crashed. I have since gotten a new one and it took me a while to come across this! I also in fact like the theme though.

  25. Hey – great blog, just looking about some blogs, seems a pretty nice platform you might be utilizing. Im currently utilizing WordPress for a few of my web sites but looking to alter 1 of them through to a platform similar to yours as being a trial run. Something in particular youd recommend about it?

  26. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.

    nonetheless, you command get got an edginess
    over that you wish be delivering the following.
    unwell unquestionably come further formerly again as exactly the same
    nearly a lot often inside case you shield this
    increase.

  27. This is such a fantastic resource that youre offering and also you give it absent free of charge. I adore seeing web websites that comprehend the value of providing a quality resource free of charge. It?s the outdated what goes about arrives around routine.

  28. Appreciating the time and energy you put into your blog and
    in depth information you present. It’s good to
    come across a blog every once in a while that isn’t the same old rehashed material.

    Wonderful read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  29. I have been exploring for a little for any high-quality articles or blog posts in this sort of area .

    Exploring in Yahoo I eventually stumbled upon this website.
    Reading this information So i’m satisfied to
    convey that I’ve an incredibly good uncanny feeling I came upon just what I needed.
    I most no doubt will make certain to do not put out of your mind
    this website and provides it a glance on a continuing basis.

  30. I like the valuable info you provide to your articles.
    I will bookmark your blog and take a look at again here frequently.
    I am rather certain I’ll learn lots of new stuff proper here!
    Best of luck for the following!

  31. hello anyone, I was just checkin out this blog and I really admire the basis of the article, and have nothing to do, so if anyone would like to to have an interesting conversation about it, please contact me on AIM, my name is rick smith

  32. Hey, I think your website might be having browser compatibility issues.
    When I look at your blog site in Safari, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to give you
    a quick heads up! Other then that, excellent blog!

  33. Today, I went to the beach with my children. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.

    There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  34. An impressive share! I’ve just forwarded this onto a colleague who has
    been doing a little homework on this. And he
    actually bought me lunch because I stumbled upon it for him…

    lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanx for spending some time to talk about this subject here on your site.

  35. This is really interesting, You’re a very skilled blogger.
    I have joined your feed and look forward to seeking more of your fantastic
    post. Also, I have shared your website in my social networks!

  36. With havin so much written content do you ever run into any issues of plagorism or copyright violation? My website
    has a lot of exclusive content I’ve either written myself
    or outsourced but it looks like a lot of it is popping it up all over the web without my permission. Do you know any
    techniques to help protect against content from being ripped off?

    I’d genuinely appreciate it.

Leave a Reply

Your email address will not be published.