---
description: What is Regular Expression? A regular expression or regex is a special text string used for describing a search pattern. Learn re module, re.match(),re.search(), re.findall(), re.split() methods in this tutorial with examples.
title: "Python RegEx: re.match(), re.search(), re.findall() with Example"
image: https://www.guru99.com/images/python-regex.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Python Regular Expressions Tutorial covers re.match, re.search, re.findall, and re.split through practical examples. Lessons explain metacharacters, character classes, groups, flags, substitution, and common patterns for text parsing and validation.

- 🔤 **re Module:** Import re to gain match, search, findall, split, sub, and compile functions for regex tasks.
- 📐 **Metacharacters:** Patterns combine dot, star, plus, anchors, and character classes to express flexible string rules.
- 🎯 **match vs search:** match anchors at the string start, while search scans the entire string for the first hit.
- 📋 **findall and split:** findall returns every non-overlapping match; split breaks a string on regex boundaries.
- 🔁 **sub Replacement:** re.sub swaps matches with new text or a callback for advanced text transformations.
- 🤖 **AI Regex Help:** AI assistants generate and explain Python regex patterns, cutting trial and error time.

Read More

![Python RegEx Tutorial](https://www.guru99.com/images/python-regex.png)

## What is Regular Expression in Python?

A **Regular Expression (RE)** in a programming language is a special text string used for describing a search pattern. It is extremely useful for extracting information from text such as code, files, log, spreadsheets or even documents.

While using the Python regular expression the first thing is to recognize is that everything is essentially a character, and we are writing patterns to match a specific sequence of characters also referred as string. Ascii or latin letters are those that are on your keyboards and Unicode is used to match the foreign text. It includes digits and punctuation and all special characters like $#@!%, etc.

For instance, a Python regular expression could tell a program to search for specific text from the string and then to print out the result accordingly. Expression can include

- Text matching
- Repetition
- Branching
- Pattern-composition etc.

Regular expression or RegEx in Python is denoted as RE (REs, regexes or regex pattern) are imported through **re module**. Python supports regular expression through libraries. RegEx in Python supports various things like **Modifiers, Identifiers, and White space characters**.

| Identifiers | Modifiers | White space characters | Escape required |
| --- | --- | --- | --- |
| \\d= any number (a digit) | \\d represents a digit.Ex: \\d{1,5} it will declare digit between 1,5 like 424,444,545 etc. | \\n = new line | . + \* ? \[] $ ^ () {} \| \\ |
| \\D= anything but a number (a non-digit) | + = matches 1 or more | \\s= space | |
| \\s = space<br> (tab,space,newline etc.) | ? = matches 0 or 1 | \\t =tab | |
| \\S= anything but a space | \* = 0 or more | \\e = escape | |
| \\w = letters ( Match alphanumeric character, including “\_”) | $ match end of a string | \\r = carriage return | |
| \\W =anything but letters ( Matches a non-alphanumeric character excluding “\_”) | ^ match start of a string | \\f= form feed | |
| . = anything but letters (periods) | \| matches either or x/y | —————– | |
| \\b = any character except for new line | \[] = range or “variance” | —————- | |
| \\. | {x} = this amount of preceding code | —————– | |

## Regular Expression(RE) Syntax

```
import re
```

- “re” module included with Python primarily used for string searching and manipulation
- Also used frequently for web page “ [Scraping](https://www.guru99.com/web-scraping-tools.html)” (extract large amount of data from websites)

We will begin the expression tutorial with this simple exercise by using the expressions (w+) and (^).

## Example of w+ and ^ Expression

- **“^”:** This expression matches the start of a string
- **“w+**“: This expression matches the alphanumeric character in the string

Here we will see a Python RegEx Example of how we can use w+ and ^ expression in our code. We cover the function re.findall() in Python, later in this tutorial but for a while we simply focus on \\w+ and \\^ expression.

For example, for our string “guru99, education is fun” if we execute the code with w+ and^, it will give the output “guru99”.

[![Example of w+ and ^ Expression]()](https://www.guru99.com/images/Pythonnew/Python14.1.png)

```
import re
xx = "guru99,education ">is fun"
r1 = re.findall(r"^\w+",xx)
print(r1)
```

Remember, if you remove +sign from the w+, the output will change, and it will only give the first character of the first letter, i.e., \[g]  

**Don't Miss:**

- [Python calendar Module with Example](https://www.guru99.com/calendar-in-python.html)
- [PyQt5 Tutorial with Examples: Create Python GUIs with Qt](https://www.guru99.com/pyqt-tutorial.html)
- [Python abs() Function: Absolute Value Examples](https://www.guru99.com/abs-in-python.html)
- [type() and isinstance() in Python with Examples](https://www.guru99.com/type-isinstance-python.html)

## Example of \\s expression in re.split function

- “s”: This expression is used for creating a space in the string

To understand how this RegEx in Python works, we begin with a simple Python RegEx Example of a split function. In the example, we have split each word using the “re.split” function and at the same time we have used expression \\s that allows to parse each word in the string separately.

[![\\s expression in re.split function]()](https://www.guru99.com/images/Pythonnew/Python14.2.png)

When you execute this code it will give you the output \[‘we’, ‘are’, ‘splitting’, ‘the’, ‘words’].

Now, let see what happens if you remove “\\” from s. There is no ‘s’ alphabet in the output, this is because we have removed ‘\\’ from the string, and it evaluates “s” as a regular character and thus split the words wherever it finds “s” in the string.

[![\\s expression in re.split function]()](https://www.guru99.com/images/Pythonnew/Python14.3.png)

Similarly, there are series of other Python regular expression that you can use in various ways in Python like \\d,\\D,$,\\.,\\b, etc.

Here is the complete code

```
import re
xx = "guru99,education ">is fun"
r1 = re.findall(r"^\w+", xx)
print((re.split(r'\s','we are splitting the words')))
print((re.split(r's','split the words')))
```

Next, we will going to see the types of methods that are used with regular expression in Python.

## Using regular expression methods

The “re” package provides several methods to actually perform queries on an input string. We will see the methods of re in Python:

- re.match()
- re.search()
- re.findall()

**Note**: Based on the regular expressions, Python offers two different primitive operations. The match method checks for a match only at the beginning of the string while search checks for a match anywhere in the string.

## re.match()

**re.match()** function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object. But if a match is found in some other line, the Python RegEx Match function returns null.

For example, consider the following code of Python re.match() function. The expression “w+” and “\\W” will match the words starting with letter ‘g’ and thereafter, anything which is not started with ‘g’ is not identified. To check match for each element in the list or string, we run the forloop in this Python re.match() Example.

[![re.match()]()](https://www.guru99.com/images/Pythonnew/Python14.4.png)

## re.search(): Finding Pattern in Text

**re.search()** function will search the regular expression pattern and return the first occurrence. Unlike Python re.match(), it will check all lines of the input string. The Python re.search() function returns a match object when the pattern is found and “null” if the pattern is not found

### How to use search()?

In order to use search() function, you need to import Python re module first and then execute the code. The Python re.search() function takes the “pattern” and “text” to scan from our main string

[![use search()]()](https://www.guru99.com/images/Pythonnew/Python14.5.png)

For example here we look for two literal strings “Software testing” “guru99”, in a text string “Software [ Testing](https://www.guru99.com/software-testing.html) is fun”. For “software testing” we found the match hence it returns the output of Python re.search() Example as “found a match”, while for word “guru99” we could not found in string hence it returns the output as “No match”.

## re.findall()

**findall()** module is used to search for “all” occurrences that match a given pattern. In contrast, search() module will only return the first occurrence that matches the specified pattern. findall() will iterate over all the lines of the file and will return all non-overlapping matches of pattern in a single step.

### How to Use re.findall() in Python?

Here we have a list of e-mail addresses, and we want all the e-mail addresses to be fetched out from the list, we use the method re.findall() in Python. It will find all the e-mail addresses from the list.

[![ Use re.findall() in Python]()](https://www.guru99.com/images/Pythonnew/Python14.6.png)

Here is the complete code for Example of re.findall()

```
import re

list = ["guru99 get", "guru99 give", "guru Selenium"]
for element in list:
    z = re.match("(g\w+)\W(g\w+)", element)
if z:
    print((z.groups()))
    
patterns = ['software testing', 'guru99']
text = 'software testing is fun?'
for pattern in patterns:
    print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ')
    if re.search(pattern, text):
        print('found a match!')
else:
    print('no match')
abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
    print(email)
```

## Python Flags

Many Python Regex Methods and Regex functions take an optional argument called Flags. This flags can modify the meaning of the given Python Regex pattern. To understand these we will see one or two example of these Flags.

Various flags used in Python includes

| Syntax for Regex Flags | What does this flag do |
| --- | --- |
| \[re.M] | Make begin/end consider each line |
| \[re.I] | It ignores case |
| \[re.S] | Make \[ . ] |
| \[re.U] | Make { \\w,\\W,\\b,\\B} follows Unicode rules |
| \[re.L] | Make {\\w,\\W,\\b,\\B} follow locale |
| \[re.X] | Allow comment in Regex |

## Example of re.M or Multiline Flags

In multiline the pattern character \[^] match the first character of the string and the beginning of each line (following immediately after the each newline). While expression small “w” is used to mark the space with characters. When you run the code the first variable “k1” only prints out the character ‘g’ for word guru99, while when you add multiline flag, it fetches out first characters of all the elements in the string.

[![Example of re.M or Multiline Flags]()](https://www.guru99.com/images/Pythonnew/Python14.7.png)

Here is the code

```
import re
xx = """guru99 
careerguru99	
selenium"""
k1 = re.findall(r"^\w", xx)
k2 = re.findall(r"^\w", xx, re.MULTILINE)
print(k1)
print(k2)
```

- We declared the variable xx for string ” guru99…. careerguru99….selenium”
- Run the code without using flags multiline, it gives the output only ‘g’ from the lines
- Run the code with flag “multiline”, when you print ‘k2’ it gives the output as ‘g’, ‘c’ and ‘s’
- So, the difference we can see after and before adding multi-lines in above example.

Likewise, you can also use other Python flags like re.U (Unicode), re.L (Follow locale), re.X (Allow Comment), etc.

### Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

```
# Example of w+ and ^ Expression
import re
xx = "guru99,education ">is fun"
r1 = re.findall(r"^\w+",xx)
print r1

# Example of \s expression in re.split function
import re
xx = "guru99,education ">is fun"
r1 = re.findall(r"^\w+", xx)
print (re.split(r'\s','we are splitting the words'))
print (re.split(r's','split the words'))

# Using re.findall for text
import re

list = ["guru99 get", "guru99 give", "guru Selenium"]
for element in list:
    z = re.match("(g\w+)\W(g\w+)", element)
if z:
    print(z.groups())
    
patterns = ['software testing', 'guru99']
text = 'software testing is fun?'
for pattern in patterns:
    print 'Looking for "%s" in "%s" ->' % (pattern, text),
    if re.search(pattern, text):
        print 'found a match!'
else:
    print 'no match'
abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
    print email

# Example of re.M or Multiline Flags
import re
xx = """guru99 
careerguru99	
selenium"""
k1 = re.findall(r"^\w", xx)
k2 = re.findall(r"^\w", xx, re.MULTILINE)
print k1
print k2

```

## Test your Python Knowledge

## 1. Which method is used to find all occurrences of a pattern in a string?

- re.search()
- re.match()
- re.findall()
- re.split()

Submit Answer

re.findall() is used to find all occurrences of a pattern in a string.

## 2. What does the \\d character class represent in regular expressions?

- Any digit (0-9)
- Any non-digit character
- Any whitespace character
- Any letter or number

Submit Answer

\\d represents any digit (0-9).

## 3. Which function would you use to split a string based on spaces?

- re.split(r’\\s’, string)
- re.findall(r’\\w+’, string)
- re.match(r’\\s+’, string)
- re.split(r’\\w+’, string)

Submit Answer

re.split(r’\\s’, string) splits a string based on spaces using the \\s expression.

## 4. What is the main difference between re.match() and re.search()?

- re.match() looks for a pattern at the start of a string, while re.search() looks for a pattern anywhere in the string.
- re.match() returns all matches, while re.search() returns the first match.
- re.search() is faster than re.match().
- Both functions behave the same way.

Submit Answer

re.match() looks for a pattern at the start of a string, while re.search() looks for a pattern anywhere in the string.

Next Question

## FAQs

⚡ What is the difference between re.match and re.search?

re.match returns a match object only when the pattern matches at the start of the string. re.search scans the entire string and returns the first match anywhere.

🤖 Can AI help write Python regex faster?

Yes. AI tools like ChatGPT, Copilot, and regex-specific assistants generate patterns from plain language, explain captures, and translate regex between languages while flagging common pitfalls.

💡 How does AI debug failing regex patterns?

AI tools highlight each metacharacter, simulate matches step by step, and suggest fixes. They identify greedy quantifier issues, missing escapes, and recommend lookaheads where needed.

📋 How do I split a string with a regex in Python?

Use re.split(pattern, string). It returns a list of substrings between matches. The pattern can capture delimiters in groups and include the captured delimiters in the result.

🔁 How do I replace text using re.sub?

Call re.sub(pattern, replacement, string). The replacement may be a literal string with backreferences such as \\\\1, or a function that returns text computed from each match object.

🎯 What do regex flags like re.IGNORECASE do?

Flags modify pattern behavior. re.IGNORECASE matches uppercase and lowercase letters interchangeably. re.MULTILINE makes ^ and $ match line boundaries instead of only string boundaries.

🛡️ Are Python regex patterns vulnerable to ReDoS attacks?

Yes. Catastrophic backtracking on nested quantifiers can hang the interpreter. Avoid patterns like (a+)+, prefer atomic groups when available, and limit input size before regex evaluation.

📚 What does re.compile do and why use it?

re.compile returns a compiled pattern object. Reusing the same pattern across many strings is faster because compilation runs only once. It also makes regex usage clearer in code.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-regex.png","url":"https://www.guru99.com/images/python-regex.png","width":"700","height":"250","caption":"Python RegEx","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html","name":"Python RegEx: re.match(), re.search(), re.findall() with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#webpage","url":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html","name":"Python RegEx: re.match(), re.search(), re.findall() with Example","dateModified":"2026-10-07T14:59:51+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-regex.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Live Project, Python","headline":"Python RegEx: re.match(), re.search(), re.findall() with Example","description":"What is Regular Expression? A regular expression or regex is a special text string used for describing a search pattern. Learn re module, re.match(),re.search(), re.findall(), re.split() methods in this tutorial with examples.","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-07T14:59:51+05:30","image":{"@id":"https://www.guru99.com/images/python-regex.png"},"copyrightYear":"2026","name":"Python RegEx: re.match(), re.search(), re.findall() with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between re.match and re.search?","acceptedAnswer":{"@type":"Answer","text":"re.match returns a match object only when the pattern matches at the start of the string. re.search scans the entire string and returns the first match anywhere."}},{"@type":"Question","name":"Can AI help write Python regex faster?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI tools like ChatGPT, Copilot, and regex-specific assistants generate patterns from plain language, explain captures, and translate regex between languages while flagging common pitfalls."}},{"@type":"Question","name":"How does AI debug failing regex patterns?","acceptedAnswer":{"@type":"Answer","text":"AI tools highlight each metacharacter, simulate matches step by step, and suggest fixes. They identify greedy quantifier issues, missing escapes, and recommend lookaheads where needed."}},{"@type":"Question","name":"How do I split a string with a regex in Python?","acceptedAnswer":{"@type":"Answer","text":"Use re.split(pattern, string). It returns a list of substrings between matches. The pattern can capture delimiters in groups and include the captured delimiters in the result."}},{"@type":"Question","name":"How do I replace text using re.sub?","acceptedAnswer":{"@type":"Answer","text":"Call re.sub(pattern, replacement, string). The replacement may be a literal string with backreferences such as \\1, or a function that returns text computed from each match object."}},{"@type":"Question","name":"What do regex flags like re.IGNORECASE do?","acceptedAnswer":{"@type":"Answer","text":"Flags modify pattern behavior. re.IGNORECASE matches uppercase and lowercase letters interchangeably. re.MULTILINE makes ^ and $ match line boundaries instead of only string boundaries."}},{"@type":"Question","name":"Are Python regex patterns vulnerable to ReDoS attacks?","acceptedAnswer":{"@type":"Answer","text":"Yes. Catastrophic backtracking on nested quantifiers can hang the interpreter. Avoid patterns like (a+)+, prefer atomic groups when available, and limit input size before regex evaluation."}},{"@type":"Question","name":"What does re.compile do and why use it?","acceptedAnswer":{"@type":"Answer","text":"re.compile returns a compiled pattern object. Reusing the same pattern across many strings is faster because compilation runs only once. It also makes regex usage clearer in code."}}]}],"@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#schema-1118475","isPartOf":{"@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/python-regular-expressions-complete-tutorial.html#webpage"}}]}
```
