

{"id":9391,"date":"2018-02-27T10:04:27","date_gmt":"2018-02-27T04:34:27","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=9391"},"modified":"2026-04-28T11:13:11","modified_gmt":"2026-04-28T05:43:11","slug":"python-regex-tutorial","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/","title":{"rendered":"Python Regex &#8211; Learn Python Regular Expression Functions"},"content":{"rendered":"<p><em>Python Regular Expression <\/em>is one of my favourite topics. Let\u2019s delve into this without wasting a moment to learn Python Regex Tutorial.<\/p>\n<p>Here, we will discuss\u00a0Metacharacters, examples &amp; functions of Python Regex. Along with this, we will cover Python findall, Python multiline.<\/p>\n<p>So, let&#8217;s start a short Python Regex Cheat Sheet.<\/p>\n<div id=\"attachment_9476\" style=\"width: 1210px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-9476\" class=\"wp-image-9476 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01.jpg\" alt=\"Python Regular Expression \/ Python Regex\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1024x536.jpg 1024w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><p id=\"caption-attachment-9476\" class=\"wp-caption-text\">Python Regular Expression \/ Python Regex<\/p><\/div>\n<h3>What is the Python Regular Expression (Regex)?<\/h3>\n<p>A regular expression, or regex, is a tiny search language baked into Python\u2019s re module. Think of it as a smart magnifying glass that finds patterns in text, not just fixed words.<\/p>\n<p>Want to spot all email addresses in a log file? A well-crafted regex can do it in one pass, saving hours of manual scanning.<\/p>\n<p>We can then use this pattern in a string-searching algorithm to \u201cfind\u201d or \u201cfind and replace\u201d on strings. You would\u2019ve seen this feature in Microsoft Word as well.<\/p>\n<p>Patterns use symbols like . (any single character), * (zero or more repeats), and [] (character sets). By mixing these, you can build powerful filters such as r&#8221;\\d{4}-\\d{2}-\\d{2}&#8221; to catch dates like 2025-07-14.<\/p>\n<p>Mastering regex unlocks fast data wrangling in web scraping, log parsing, and form validation.<\/p>\n<p>In this Python Regex tutorial, we will learn the basics of regular expressions in Python. For this, we will use the \u2018re\u2019 module.<\/p>\n<p>Let\u2019s import it before we begin.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; import re<\/pre>\n<h3>Python Regex &#8211; Metacharacters<\/h3>\n<p>Each character in a Python Regex is either a metacharacter or a regular character. A metacharacter has a special meaning, while a regular character matches itself.<\/p>\n<p>Python has the following metacharacters:<\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Metacharacter<\/b><\/td>\n<td><b>Description<\/b><\/td>\n<\/tr>\n<tr>\n<td>^<\/td>\n<td>Matches the start of the string<\/td>\n<\/tr>\n<tr>\n<td>.<\/td>\n<td>Matches a single character, except a newline<br \/>\nBut when used inside square brackets, a dot is matched<\/td>\n<\/tr>\n<tr>\n<td>[ ]<\/td>\n<td>A bracket expression matches a single character from the ones inside it<br \/>\n[abc] matches \u2018a\u2019, \u2018b\u2019, and \u2018c\u2019<br \/>\n[a-z] matches characters from \u2018a\u2019 to \u2018z\u2019<br \/>\n[a-cx-z] matches \u2018a\u2019, \u2019b\u2019, \u2019c\u2019, \u2019x\u2019, \u2019y\u2019, and \u2018z\u2019<\/td>\n<\/tr>\n<tr>\n<td>[^ ]<\/td>\n<td>Matches a single character from those except the ones mentioned in the brackets[^abc] matches all characters except \u2018a\u2019, \u2018b\u2019 and \u2018c\u2019<\/td>\n<\/tr>\n<tr>\n<td>( )<\/td>\n<td>Parentheses define a marked subexpression, also called a block, or a capturing group<\/td>\n<\/tr>\n<tr>\n<td>\\t, \\n, \\r, \\f<\/td>\n<td>Tab, newline, return, form feed<\/td>\n<\/tr>\n<tr>\n<td>*<\/td>\n<td>Matches the preceding character zero or more times<br \/>\nab*c matches \u2018ac\u2019, \u2018abc\u2019, \u2018abbc\u2019, and so on<br \/>\n[ab]* matches \u2018\u2019, \u2018a\u2019, \u2018b\u2019, \u2018ab\u2019, \u2018ba\u2019, \u2018aba\u2019, and so on<br \/>\n(ab)* matches \u2018\u2019, \u2018ab\u2019, \u2018abab\u2019, \u2018ababab\u2019, and so on<\/td>\n<\/tr>\n<tr>\n<td>{m,n}<\/td>\n<td>Matches the preceding character minimum m times, and maximum n times<br \/>\na{2,4} matches \u2018aa\u2019, \u2018aaa\u2019, and \u2018aaaa\u2019<\/td>\n<\/tr>\n<tr>\n<td>{m}<\/td>\n<td>Matches the preceding character exactly m times<\/td>\n<\/tr>\n<tr>\n<td>?<\/td>\n<td>Matches the preceding character zero or one times<br \/>\nab?c matches \u2018ac\u2019 or \u2018abc\u2019<\/td>\n<\/tr>\n<tr>\n<td>+<\/td>\n<td>Matches the preceding character one or one times<br \/>\nab+c matches \u2018abc\u2019, \u2018abbc\u2019, \u2018abbbc\u2019, and so on, but not \u2018ac\u2019<\/td>\n<\/tr>\n<tr>\n<td>|<\/td>\n<td>The choice operator matches either the expression before it, or the one after<br \/>\nabc|def matches \u2018abc\u2019 or \u2018def\u2019<\/td>\n<\/tr>\n<tr>\n<td>\\w<\/td>\n<td>Matches a word character (a-zA-Z0-9)<br \/>\n\\W matches single non-word characters<\/td>\n<\/tr>\n<tr>\n<td>\\b<\/td>\n<td>Matches the boundary between word and non-word characters<\/td>\n<\/tr>\n<tr>\n<td>\\s<\/td>\n<td>Matches a single whitespace character<br \/>\n\\S matches a single non-whitespace character<\/td>\n<\/tr>\n<tr>\n<td>\\d<\/td>\n<td>Matches a single decimal digit character (0-9)<\/td>\n<\/tr>\n<tr>\n<td>\\<\/td>\n<td>A single backslash inhibits a character\u2019s specialness<br \/>\nExamples- \\. \u00a0\u00a0\u00a0\\\\ \u00a0\u00a0\u00a0\u00a0\\*<br \/>\nWhen unsure if a character has a special meaning, put a \\ before it:<br \/>\n\\@<\/td>\n<\/tr>\n<tr>\n<td>$<\/td>\n<td>A dollar matches the end of the string<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>A raw string literal does not handle backslashes in any special way. For this, prepend an \u2018r\u2019 before the pattern.<\/p>\n<p>Without this, you may have to use \u2018\\\\\\\\\u2019 for a single backslash character. But with this, you only need r\u2019\\\u2019.<\/p>\n<p>Regular characters match themselves.<\/p>\n<h3>Rules for a Match in regex<\/h3>\n<p>So, how does this work? The following rules must be met:<\/p>\n<ol>\n<li>The search scans the string start to end.<\/li>\n<li>The whole pattern must match, but not necessarily the whole string.<\/li>\n<li>The search stops at the first match.<\/li>\n<\/ol>\n<p>If a match is found, the group() method returns the matching phrase. If not, it returns None.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; print(re.search('na','no'))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>None<\/p>\n<\/div>\n<p>Let\u2019s look at about a couple important functions now.<\/p>\n<h3>Python Regular Expression Functions<\/h3>\n<p>We have a few functions to help us use Python regex.<\/p>\n<h4>1. match() in python<\/h4>\n<p>match() takes two arguments- a pattern and a string. If they match, it returns the string. Else, it returns None.<\/p>\n<p>Let\u2019s take a few Python regular expression match examples.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; print(re.match('center','centre'))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>None<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; print(re.match('...\\w\\we','centre'))<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;_sre.SRE_Match object; span=(0, 6), match=&#8217;centre&#8217;&gt;<\/p>\n<\/div>\n<h4>2. search() in python<\/h4>\n<p>search(), like match(), takes two arguments- the pattern and the string to be searched.<\/p>\n<p>Let\u2019s take a few examples.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('aa?yushi','ayushi')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;ayushi&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('aa?yushi?','ayush ayushi')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;ayush&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('\\w*end','Hey! What are your plans for the weekend?')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;weekend&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('^\\w*end','Hey! What are your plans for the weekend?')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#337&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>match.group()<\/p>\n<p>AttributeError: &#8216;NoneType&#8217; object has no attribute &#8216;group&#8217;<\/p>\n<\/div>\n<p>Here, an AttributeError raised because it found no match. This is because we specified that this pattern should be at the beginning of the string.<\/p>\n<p>Let\u2019s try searching for space.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('i\\sS','Ayushi Sharma')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;i S&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search('\\w+c{2}\\w*','Occam\\'s Razor')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;Occam&#8217;<\/p>\n<\/div>\n<p>It really will take some practice to get it into habit what the metacharacters mean.<\/p>\n<p>But since we don\u2019t have so many, this will hardly take an hour.<\/p>\n<h3>Python Regex Examples<\/h3>\n<p>Let\u2019s try crafting a Python regex for an email address. Hmm, so what does one look like? It looks like this: <a href=\"mailto:abc-def@ghi.com\">abc-def@ghi.com<\/a><\/p>\n<p>Let\u2019s try the following code:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search(r'[\\w.-]+@[\\w-]+\\.[\\w]+','Please mail it to ayushiwasthere@gmail.com')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;ayushiwasthere@gmail.com&#8217;It worked perfectly!<\/p>\n<\/div>\n<p>Here, if you would have typed [\\w-.] instead of [\\w.-], it would have raised the following error:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search(r'[\\w-.]+@[\\w-]+\\.[\\w]+','Please mail it to ayushiwasthere@gmail.com')\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#347&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>match=re.search(r'[\\w-.]+@[\\w-]+\\.[\\w]+&#8217;,&#8217;Please mail it to ayushiwasthere@gmail.com&#8217;)<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\re.py&#8221;, line 182, in search<br \/>\nreturn _compile(pattern, flags).search(string)<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\re.py&#8221;, line 301, in _compile<\/p>\n<p>p = sre_compile.compile(pattern, flags)<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\sre_compile.py&#8221;, line 562, in compile<\/p>\n<p>p = sre_parse.parse(p, flags)<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\sre_parse.py&#8221;, line 856, in parse<\/p>\n<p>p = _parse_sub(source, pattern, flags &amp; SRE_FLAG_VERBOSE, False)<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\sre_parse.py&#8221;, line 415, in _parse_sub<\/p>\n<p>itemsappend(_parse(source, state, verbose))<\/p>\n<p>File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\sre_parse.py&#8221;, line 547, in _parse<\/p>\n<p>raise source.error(msg, len(this) + 1 + len(that))<\/p>\n<p>sre_constants.error: bad character range \\w-. at position 1<\/p>\n<\/div>\n<p>This is because normally, we use a dash (-) to indicate a range.<\/p>\n<h4>Group Extraction in regex<\/h4>\n<p>Let\u2019s continue with the example on emails. What if you only want the username?<\/p>\n<p>For this, you can provide an argument(like an index) to the group() method.<\/p>\n<p>Take a look at this:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.search(r'([\\w.-]+)@([\\w-]+)\\.([\\w]+)','Please mail it to ayushiwasthere@gmail.com')\r\n&gt;&gt;&gt; match.group()<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;ayushiwasthere@gmail.com&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match.group(1)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;ayushiwasthere&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match.group(2)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;gmail&#8217;<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match.group(3)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&#8216;com&#8217;<\/p>\n<\/div>\n<p>Parentheses let you extract the parts you want. Note that for this, we divided the pattern into groups using parentheses:<\/p>\n<p>r'([\\w.-]+)@([\\w-]+)\\.([\\w]+)&#8217;<\/p>\n<h4>Python findall()<\/h4>\n<p>Above, we saw that Python regex search() stops at the first match.<\/p>\n<p>But Python findall() returns a list of all matches found.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'advi[cs]e','I could advise you on your poem, but you would disparage my advice')<\/pre>\n<p>We can then iterate on it.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; for i in match:\r\n     print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">advise<br \/>\nadvice<\/div>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; type(match)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&lt;class &#8216;list&#8217;&gt;<\/div>\n<h4>findall() with Files in Python<\/h4>\n<p>We have worked with <a href=\"https:\/\/data-flair.training\/blogs\/python-file\/\">files<\/a>, and we know how to read and write them. Why not make life easier by using Python findall() with files?<\/p>\n<p>We\u2019ll first use the os module to get to the desktop. Let\u2019s see.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; import os\r\n&gt;&gt;&gt; os.chdir('C:\\\\Users\\\\lifei\\\\Desktop')\r\n&gt;&gt;&gt; f=open('Today.txt')<\/pre>\n<p>We have a file called Today.txt on our Desktop. These are its contents:<\/p>\n<p>OS, DBMS, DS, ADA<\/p>\n<p>HTML, CSS, jQuery, JavaScript<\/p>\n<p>Python, C++, Java<\/p>\n<p>This sem&#8217;s subjects<\/p>\n<p>Now, let\u2019s call findall().<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'Java[\\w]*',f.read())<\/pre>\n<p>Finally, let\u2019s iterate on it.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; for i in match:\r\n      print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">JavaScript<br \/>\nJava<\/div>\n<h4>findall() with Groups in Python<\/h4>\n<p>We saw how we can divide a pattern into groups using parentheses. Watch what happens when we call Python Regex findall().<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'([\\w]+)\\s([\\w]+)','Ayushi Sharma, Fluffy Sharma, Leo Sharma, Candy Sharma')\r\n&gt;&gt;&gt; for i in match:\r\n   print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>(&#8216;Ayushi&#8217;, &#8216;Sharma&#8217;)<\/p>\n<p>(&#8216;Fluffy&#8217;, &#8216;Sharma&#8217;)<\/p>\n<p>(&#8216;Leo&#8217;, &#8216;Sharma&#8217;)<\/p>\n<p>(&#8216;Candy&#8217;, &#8216;Sharma&#8217;)<\/p>\n<\/div>\n<h3>Python Regex Options<\/h3>\n<p>The functions we discussed may also take an optional argument. These options are:<\/p>\n<h4>1. Python Regular Expression IGNORECASE<\/h4>\n<p>This Python regex ignores case while matching.<\/p>\n<p>Take this example of Python Regex IGNORECASE:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'hi','Hi, did you ship it, Hillary?',re.IGNORECASE)\r\n&gt;&gt;&gt; for i in match:\r\n      print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Hihi<\/p>\n<p>Hi<\/p>\n<\/div>\n<h4>2. Python MULTILINE<\/h4>\n<p>When working with a multi-line string, ^ and $ match the start and end of each line, not just the whole string.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'^Hi','Hi, did you ship it, Hillary?\\nNo, I didn\\'t, but Hi',re.MULTILINE)\r\n&gt;&gt;&gt; for i in match:\r\n      print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Hi<\/div>\n<h4>3. Python DOTALL<\/h4>\n<p>.* does not scan everything in a multiline string; it only matches the first line. This is because. does not match a newline.<\/p>\n<p>To allow this, we use DOTALL.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'.*','Hi, did you ship it, Hillary?\\nNo, I didn\\'t, but Hi',re.DOTALL)\r\n&gt;&gt;&gt; for i in match:\r\n     print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Hi, did you ship it, Hillary?No, I didn&#8217;t, but Hi<\/div>\n<h3>Greedy vs Non-Greedy<\/h3>\n<p><strong>Advantages and disadvantages of greedy and non- greedy:<\/strong><\/p>\n<p><strong>1. Greedy:<\/strong><\/p>\n<ul>\n<li><strong>Advantage:<\/strong> It works fast for simple patterns and captures as much text as possible.<\/li>\n<li><strong>Disadvantage:<\/strong> It might capture more text than required.<\/li>\n<\/ul>\n<p><strong>2. Non-greedy:<\/strong><\/p>\n<ul>\n<li><strong>Advantage:<\/strong> It stops as soon as it finds its first match.<\/li>\n<li><strong>Disadvantage:<\/strong> As it checks more possibilities, it becomes slower.<\/li>\n<\/ul>\n<p>The metacharacters *, +, and ? are greedy. This means that they keep searching. Let\u2019s take an example.<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'(&lt;.*&gt;)','&lt;em&gt;Strong&lt;\/em&gt; &lt;i&gt;Italic&lt;\/i&gt;')\r\n&gt;&gt;&gt; for i in match:\r\n     print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;em&gt;&lt;\/em&gt;<\/p>\n<p>&lt;i&gt;<\/p>\n<p>&lt;\/i&gt;<\/p>\n<\/div>\n<p>This gave us the whole string, because it greedily keeps searching. What if we just want the opening and closing tags? Look:<\/p>\n<p>print(i)<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'(&lt;.*?&gt;)','&lt;em&gt;Strong&lt;\/em&gt; &lt;i&gt;Italic&lt;\/i&gt;')\r\n&gt;&gt;&gt; for i in match:\r\n       print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;em&gt;&lt;\/em&gt;<\/p>\n<p>&lt;i&gt;<\/p>\n<p>&lt;\/i&gt;<\/p>\n<\/div>\n<p>The .* is greedy, and the ? makes it non-greedy.<\/p>\n<p>Alternatively, we could also do this:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall(r'&lt;\/?\\w+&gt;','&lt;em&gt;Strong&lt;\/em&gt; &lt;i&gt;Italic&lt;\/i&gt;')\r\n&gt;&gt;&gt; for i in match:\r\n     print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>&lt;em&gt;&lt;\/em&gt;<\/p>\n<p>&lt;i&gt;<\/p>\n<p>&lt;\/i&gt;<\/p>\n<\/div>\n<p>Here\u2019s another example:<\/p>\n<pre class=\"EnlighterJSRAW\">&gt;&gt;&gt; match=re.findall('(a*?)b','aaabbc')\r\n&gt;&gt;&gt; for i in match:\r\n     print(i)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">aaa<\/div>\n<p>Here, the ? makes * non-greedy. Also, if we had skipped the b after the ?, it would have returned an empty string.<\/p>\n<p>The ? here needs a character after it to stop at. This works for all three- *?, +?, and ??.<\/p>\n<p>Similarly, {m,n}? makes it non-greedy, and matches as few occurrences as possible.<\/p>\n<h3>Substitution<\/h3>\n<p>We can use the sub() function to substitute the part of a string with another. sub() takes three arguments- pattern, substring, and string.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; re.sub('^a','an','a apple')<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&#8216;an apple&#8217;<\/div>\n<p>Here, we used ^ so it won\u2019t change apple to anpple. The grammar police approve.<\/p>\n<h3>Python Regex Applications<\/h3>\n<p>So, we learned so much about Python regular expressions, but where do we use them? They find use in these places:<\/p>\n<ul>\n<li>Search engines<\/li>\n<li>Find and Replace dialogues of word processors and text editors<\/li>\n<li>Text processing utilities like sed and AWK<\/li>\n<li>Lexical analysis<\/li>\n<\/ul>\n<p>This was all about the Python Regex Tutorial<\/p>\n<h3>Python Interview Questions on Regular Expressions<\/h3>\n<p>1. What is a regular expression in Python? Explain with an example.<\/p>\n<p>2. How to use regular expressions in Python?<\/p>\n<p>3. What is the meaning of the question mark in a regular expression in Python?<\/p>\n<p>4. How to split a regular expression in Python?<\/p>\n<p>5. How to check if a regular expression is in Python?<\/p>\n<h3>Conclusion<\/h3>\n<p>These were the basics of Python regular expressions. Honestly, we think it is really cool to have such a tool in hand.<\/p>\n<p>If you love English, try experimenting and make a small project with it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python Regular Expression is one of my favourite topics. Let\u2019s delve into this without wasting a moment to learn Python Regex Tutorial. Here, we will discuss\u00a0Metacharacters, examples &amp; functions of Python Regex. Along with&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":36366,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[10342,10539,10691,10800,10802,10804,10807,36650,36651],"class_list":["post-9391","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-3-regex","tag-python-findall","tag-python-multiline","tag-python-regex","tag-python-regex-example","tag-python-regex-tutorial","tag-python-regular-expressions","tag-regex-in-python","tag-rules-for-match-in-regex"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Regex - Learn Python Regular Expression Functions - DataFlair<\/title>\n<meta name=\"description\" content=\"Python Regex tutorial - Python3 Regular expression with examples, Python Regex Metacharacter, Python findall, Python multiline.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Regex - Learn Python Regular Expression Functions - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python Regex tutorial - Python3 Regular expression with examples, Python Regex Metacharacter, Python findall, Python multiline.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-02-27T04:34:27+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-04-28T05:43:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Regex - Learn Python Regular Expression Functions - DataFlair","description":"Python Regex tutorial - Python3 Regular expression with examples, Python Regex Metacharacter, Python findall, Python multiline.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"Python Regex - Learn Python Regular Expression Functions - DataFlair","og_description":"Python Regex tutorial - Python3 Regular expression with examples, Python Regex Metacharacter, Python findall, Python multiline.","og_url":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-02-27T04:34:27+00:00","article_modified_time":"2026-04-28T05:43:11+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Python Regex &#8211; Learn Python Regular Expression Functions","datePublished":"2018-02-27T04:34:27+00:00","dateModified":"2026-04-28T05:43:11+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/"},"wordCount":1845,"commentCount":3,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg","keywords":["Python 3 regex","Python findall","python multiline","Python Regex","Python Regex example","Python Regex Tutorial","Python Regular Expressions","regex in python","rules for match in regex"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/","url":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/","name":"Python Regex - Learn Python Regular Expression Functions - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg","datePublished":"2018-02-27T04:34:27+00:00","dateModified":"2026-04-28T05:43:11+00:00","description":"Python Regex tutorial - Python3 Regular expression with examples, Python Regex Metacharacter, Python findall, Python multiline.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/02\/Regular-Expressions-in-Python-01-1.jpg","width":1200,"height":628,"caption":"Learn Python Regex Tutorial - Python Regular Expression Functions"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-regex-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Regex &#8211; Learn Python Regular Expression Functions"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/9391","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=9391"}],"version-history":[{"count":23,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/9391\/revisions"}],"predecessor-version":[{"id":147977,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/9391\/revisions\/147977"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/36366"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=9391"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=9391"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=9391"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}