<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zohaib Shahzad on Medium]]></title>
        <description><![CDATA[Stories by Zohaib Shahzad on Medium]]></description>
        <link>https://medium.com/@zohaibshahzadTO?source=rss-bbde1faf3db7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Qo21dHnm5dLbFT_k.jpg</url>
            <title>Stories by Zohaib Shahzad on Medium</title>
            <link>https://medium.com/@zohaibshahzadTO?source=rss-bbde1faf3db7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:01:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zohaibshahzadTO/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Regular Expressions: Sub() Method and Verbose Mode]]></title>
            <link>https://medium.com/swlh/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1902cbc0ceef</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 15:31:00 GMT</pubDate>
            <atom:updated>2020-08-26T22:32:11.834Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>If you’ve stumbled across this article and are new to this series of tutorials on regular expressions, feel free to take a look at the rest of the series (in order):</p><ol><li><a href="https://medium.com/swlh/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/swlh/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><h3><strong>Substituting Strings with the Sub() Method</strong></h3><p>Regular expressions can not only find text patterns but can also substitute new text in place of those patterns. The <strong><em>sub()</em></strong> method for regex objects is passed two arguments. The first argument is a string to replace any matches. The second argument is the string for the regular expression. The <strong><em>sub()</em></strong> method returns a string with the substitutions applied.</p><p>Let’s take a look at the following example:</p><h4><strong>Example 1: Using the sub() method</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/222991e1e708d6d975daf0d8951ddaca/href">https://medium.com/media/222991e1e708d6d975daf0d8951ddaca/href</a></iframe><p>We can see that we’re trying to find all word occurrences that follow the word <strong>“Agent”</strong>. We used the <strong><em>findall()</em></strong> method and it returned <strong>“Agent Zohaib” and “Agent Bob”</strong>.</p><p>Now maybe we want to redact some words from a string.</p><pre><strong>namesRegex.sub(‘REDACTED’, ‘Agent Zohaib gave the secret documents to Agent Bob.’)</strong></pre><pre># ‘REDACTED gave the secret documents to REDACTED.’</pre><p>The word<strong> “REDACTED”</strong> was substituted for every string that matched the regex pattern within the string.</p><h4><strong>Example 2: Using Groups when implementing sub() Method</strong></h4><p>Sometimes you may need to use the matched text itself as part of the substitution. In the first argument to <strong><em>sub()</em></strong>, you can type <strong>\1</strong>, <strong>\2</strong>, <strong>\3</strong>, and so on, to mean <strong>“Enter the text of group 1, 2, 3, and so on, in the substitution.”</strong></p><p>For example, say you want to censor the names of the secret agents by showing just the first letters of their names. To do this, you could use the regex, <strong>Agent (\w)\w*</strong> and pass <strong>r’\1****’</strong> as the first argument to <strong><em>sub()</em></strong>. The <strong>\1</strong> in that string will be replaced by whatever text was matched by <strong>group 1 </strong>— that is, the <strong>(\w) </strong>group of the regular expression.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99ad8b44dea88b6845847eb28f0da311/href">https://medium.com/media/99ad8b44dea88b6845847eb28f0da311/href</a></iframe><h3><strong>Managing Complex Regular Expression’s using VERBOSE Mode</strong></h3><p>Regular expressions are fine if the text pattern you need to match is simple. But matching complicated text patterns might require long, convoluted regular expressions. You can mitigate this by telling the <strong><em>re.compile()</em></strong> function to ignore white space and comments inside the regular expression string. This <strong><em>verbose mode</em></strong> can be enabled by passing the variable<strong><em> re.VERBOSE </em></strong>as the second argument to <strong><em>re.compile()</em></strong>.</p><h4><strong>Example 3: Implementing VERBOSE Mode</strong></h4><p>Take a look at the following:</p><pre><strong>phoneRegex = re.compile(r’((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s*(ext|x|ext.)\s*\d{2,5})?)’)</strong></pre><p>That look’s really messy and it’s hard to read.</p><p>We can actually use VERBOSE mode and spread the regex over multiple lines with comments like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4da4d169658d33a3a93b938c371e8167/href">https://medium.com/media/4da4d169658d33a3a93b938c371e8167/href</a></iframe><p>Now this looks much cleaner and easier to read.</p><p>Note how this example uses a <strong>triple quote syntax (r’’’)</strong> instead of the usual single quote raw string (r’). We use the triple quote syntax so we can spread the regex over many lines, making it more legible.</p><p>The comment rules inside the regex string are the same as regular Python code: the # symbol and everything following it are ignored. Moreover, the extra spaces inside the multi-line string for the regex are not considered part of the text pattern to be matched. Overall, it helps organize your regex.</p><p>This article concludes the end of this series of tutorials on regular expression’s. I really hope I did a service in putting this series out and there and that you learned something from this.</p><p>Stay tuned for future tutorials and give this article a clap if you liked it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1902cbc0ceef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef">Regular Expressions: Sub() Method and Verbose Mode</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regular Expressions: Dot-Star and the Caret/Dollar Characters]]></title>
            <link>https://medium.com/swlh/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5458c52ad2a9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 16:01:01 GMT</pubDate>
            <atom:updated>2020-08-26T22:30:55.324Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>If you’ve stumbled across this article and are new to this series of tutorials on regular expressions, feel free to take a look at the rest of the series (in order):</p><ol><li><a href="https://medium.com/@zohaibshahzadTO/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><h3><strong>The Caret Symbol (^)</strong></h3><p>You can use the caret symbol <strong>(^)</strong> at the start of a regular expression to indicate that a match must occur at the beginning of the searched text.</p><p>If we apply the following regular expression <strong>^a</strong> (if <strong>a</strong> is the starting symbol) to input string <strong>abc</strong>, it matches <strong>a</strong>. But if we apply regular expression <strong>^b</strong> on that same input string it does not match anything. This is because within the input string <strong>abc</strong>,<strong> b</strong> is not the starting symbol. Let’s take a look at another regular expression <strong>^(T|t)he </strong>which means: uppercase character <strong>T</strong> or lowercase character <strong>t</strong> is the start symbol of the input string, followed by lowercase character <strong>h</strong>, followed by lowercase character <strong>e</strong>.</p><pre><strong>^(T|t)he =&gt; The car is parked in the garage</strong></pre><p><a href="https://regex101.com/r/nDpQKu/1"><strong>Test the regular expression</strong></a></p><h4>Example 1: Implementing Caret Symbol (^)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5e39e1dcecb3390c6179a70a30545f/href">https://medium.com/media/fd5e39e1dcecb3390c6179a70a30545f/href</a></iframe><h3><strong>The Dollar Sign ($)</strong></h3><p>Likewise, you can put a <strong>dollar sign ($)</strong> at the end of the regex to indicate the string must end with that regex pattern.</p><h4>Example 2: Implementing Dollar Symbol ($)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5de59c25234dfcdc5375c6bc4519ed2/href">https://medium.com/media/e5de59c25234dfcdc5375c6bc4519ed2/href</a></iframe><h4>Example 3: Implementing Both Caret (^) &amp; Dollar Symbol ($)</h4><p>Moreover, you can use the <strong>^</strong> and <strong>$</strong> together to indicate that the entire string must match the regex — that is, it’s not enough for a match to be made on some subset of the string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8865fc475ac10aa7ce32595cbe25ab43/href">https://medium.com/media/8865fc475ac10aa7ce32595cbe25ab43/href</a></iframe><h3><strong>The Wildcard Character</strong></h3><p>The period <strong>.</strong> (or dot) character in regex is called a wildcard because it matches <strong>any character</strong> except for a newline.</p><h4><strong>Example 4: Implementing Wildcard</strong></h4><pre><strong>atRegex = re.compile(r’.at’)</strong> # returns anything with ‘at’ followed after</pre><pre><strong>atRegex.findall(‘The cat in the hat sat on the flat mat’)</strong></pre><pre># return: [‘cat’, ‘hat’, ‘sat’, ‘lat’, ‘mat’]</pre><h4><strong>NOTE:</strong></h4><p>the <strong>dot character</strong> will match just o<strong>ne character</strong>, which is why the match for the text “<strong><em>flat</em></strong>” in this example matched only “<strong><em>lat</em></strong>”. To match an actual dot, escape the dot with a backslash: \</p><h4><strong>Example 5: Wildcard with Repetition</strong></h4><pre><strong>atRegex = re.compile(r’.{1,2}at’)</strong></pre><p>With regard to<strong> {1, 2}</strong>, it means any <strong>1 or 2</strong> characters (even white spaces), followed by “<strong><em>at</em></strong>”.</p><h3><strong>Matching Everything with Dot-Star</strong></h3><h4>Example 6: Implementing Dot-Star</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8865fc475ac10aa7ce32595cbe25ab43/href">https://medium.com/media/8865fc475ac10aa7ce32595cbe25ab43/href</a></iframe><p>The <strong>dot-star (.*)</strong> uses <strong>greedy mode</strong>.<strong> </strong>It will always try to match as much text as possible. To match any and all text in a non-greedy fashion, use the <strong>dot, star, and question mark (.*?)</strong>. Similarly with braces, the question mark tells Python to match in a non-greedy way.</p><h4><strong>Example 7: Implementing a Non-Greedy Search (.*?)</strong></h4><pre><strong>serve = ‘&lt;To serve humans&gt; for dinner.&gt;’</strong></pre><pre><strong>nongreedy = re.compile(r’&lt;(.*?)&gt;’)</strong></pre><pre><strong>nongreedy.findall(serve)</strong> # [‘To serve humans’]</pre><p>Both regular expression’s roughly translate to <strong>“Match an opening angle bracket, followed by anything, followed by a closing angle bracket.”</strong> But the string <strong>“&lt;To serve man&gt; for dinner.&gt;”</strong> has two possible matches for the closing angle bracket. In the non-greedy version of the regex, Python matches the shortest possible string: <strong>“&lt;To serve man&gt;”</strong>. In the greedy version, Python matches the longest possible string: <strong>“&lt;To serve man&gt; for dinner.&gt;”</strong>.</p><h3><strong>Matching Newlines with the Dot Character</strong></h3><p>Recall that the <strong>dot-star (.*) </strong>will match everything except a newline <strong>(\n)</strong>. However, you can pass a second argument called<strong><em> re.DOTALL </em></strong>to <strong><em>re.compile()</em></strong> and by doing that you can make the dot character match <strong>ALL</strong> characters, including the newline character <strong>(\n)</strong>.</p><h4><strong>Example 8: Dot-Star with re.DOTALL</strong></h4><pre><strong>prime = ‘Serve the public trust.\nProtect the innocent.\nUpload the law.’</strong></pre><pre><strong>noNewlineRegex = re.compile(r’.*’)</strong></pre><pre><strong>noNewlineRegex.search(prime)</strong></pre><p>Just to reiterate, the above example does not implement the <strong><em>re.DOTALL</em></strong> as a second argument. Therefore, it only matches up to <strong>“Serve the public trust.”</strong></p><pre><strong>newlineRegex = re.compile(r’.*’, re.DOTALL)</strong></pre><pre><strong>newlineRegex.search(‘Serve the public trust.\nProtect the innocent.</strong></pre><pre><strong>\nUphold the law.’).group()</strong></pre><p>The regex <strong><em>noNewlineRegex</em></strong>, which did not have <strong><em>re.DOTALL</em></strong> passed to the <strong><em>re.compile()</em></strong> call that created it, will match everything only up to the first newline character, whereas <strong><em>newlineRegex</em></strong>, which did have <strong><em>re.DOTALL</em></strong> passed to <strong><em>re.compile()</em></strong>, matches everything. This is why the <strong><em>newlineRegex.search() </em></strong>call matches the full string, including its newline characters.</p><h3><strong>Another Second Argument: re.IGNORECASE</strong></h3><p>Another second argument you can implement within the <strong><em>re.compile()</em></strong> method is <strong><em>re.IGNORECASE</em></strong>.</p><p><strong><em>re.IGNORECASE</em></strong> simply makes it so that the interpreter does not care about letter case when matching strings according to Regex.</p><h4><strong>Example 9: Using re.IGNORECASE for case insensitive matching</strong></h4><pre><strong>vowelRegex = re.compile(r’[aeiou]’)</strong></pre><pre><strong>vowelRegex.findall(‘Al, why do you talk about Regex so much?’)</strong></pre><pre># return: [‘o’, ‘e’, ‘o’, ‘u’, ‘o’, ‘a’, ‘i’, ‘o’, ‘o’, ‘a’, ‘a’, ‘o’, ‘u’, ‘o’, ‘o’, ‘o’, ‘o’, ‘u’]</pre><p>Notice, how the regex matched only the lowercase vowels and ignored the uppercase A from “Al”.</p><p>Now let’s implement the re.IGNORECASE argument.</p><pre><strong>vowelRegex = re.compile(r’[aeiou]’, re.IGNORECASE)</strong></pre><pre># return: [‘A’, ‘o’, ‘e’, ‘o’, ‘u’, ‘o’, ‘a’, ‘i’, ‘o’, ‘o’, ‘a’, ‘a’, ‘o’, ‘u’, ‘o’, ‘o’, ‘o’, ‘o’, ‘u’]</pre><p>Now that we’ve implemented the <strong><em>re.IGNORECASE</em></strong> argument, it takes into account all vowels regardless of letter case. You can also use <strong><em>re.I</em></strong> as an alternative to <strong><em>re.IGNORECASE</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5458c52ad2a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9">Regular Expressions: Dot-Star and the Caret/Dollar Characters</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regular Expressions: Character Classes & findall() Method]]></title>
            <link>https://medium.com/swlh/regular-expressions-character-classes-findall-method-c4b4d71d353a?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4b4d71d353a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 16:01:01 GMT</pubDate>
            <atom:updated>2020-08-26T22:30:09.781Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>If you’ve stumbled across this article and are new to this series of tutorials on regular expressions, feel free to take a look at the rest of the series (in order):</p><ol><li><a href="https://medium.com/@zohaibshahzadTO/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><p>Before we dive into character classes for regular expressions, I want to make the distinction between the <strong><em>search()</em></strong> and <strong><em>findall()</em></strong> methods for Python regex.</p><pre><strong>search(): </strong>method finds the first match and returns it as a match object.</pre><pre><strong>findall(): </strong>method finds all instances that match the regex pattern and returns the matches as a list of strings.</pre><h3><strong>Character Classes</strong></h3><p>In the previous regex tutorials, we learned that <strong><em>\d</em></strong> could stand for any numeric digits. You could also say that <strong><em>\d</em></strong> is the shorthand for the regex <strong>(0|1|2|3|4|5|6|7|8|9)</strong>. In addition, there are many shorthand character classes shown in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jshJq5adDa4E4UMCpKsvng.png" /></figure><p>Character classes are nice for shortening regular expressions. The character class <strong>[0–5]</strong> will match only the numbers <strong>0–5</strong>; this is much shorter than typing <strong>(0|1|2|3|4|5)</strong>. Note that while <strong><em>\d</em></strong> matches digits and <strong><em>\w</em></strong> matches digits, letters, and the underscore, there is no shorthand character class that matches <strong>only letters</strong>. However, with character classes you can use the <strong>[a-zA-Z]</strong> which we’ll explore soon.</p><p>Enter the following into the interactive shell:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cda80d0fde283adb6616cb4e5eb560d/href">https://medium.com/media/5cda80d0fde283adb6616cb4e5eb560d/href</a></iframe><p>The regex <strong><em>\d+\s\w+</em></strong> will match text that has one or more numeric digits <strong>(\d+)</strong>, followed by a white space character <strong>(\s)</strong>, followed by one or more letter/digit/underscore characters <strong>(\w+)</strong>. The <strong><em>findall()</em></strong> method returns all matching strings of the regex pattern in a list.</p><h3><strong>Making Your Own Character Classes</strong></h3><p>There are times when you want to match a set of characters but the shorthand character classes (<strong>\d, \w, \s, and so on)</strong> are too broad. You can define your own character class using square brackets.</p><p>Square brackets are used to specify character sets. Use a hyphen inside a character set to specify the characters’ range. The order of the character range inside square brackets doesn’t matter. For example, the regular expression <strong><em>[Tt]he</em></strong> means: an uppercase<strong> T</strong> or lowercase <strong>t</strong>, followed by the letter <strong>h</strong>, followed by the letter <strong>e</strong>.</p><pre><strong>[Tt]he =&gt; The car parked in the garage.</strong></pre><p><a href="https://regex101.com/r/2D5zvc/1"><strong>Test the regular expression</strong></a></p><p>A period inside a character set, however, means a literal period. The regular expression <strong><em>ar[.] </em></strong>means: a lowercase character <strong>a</strong>, followed by letter <strong>r</strong>, followed by a period <strong>.</strong> character.</p><pre><strong>ar[.] =&gt; A garage is a good place to park a car.</strong></pre><p><a href="https://regex101.com/r/OgQk3y/1"><strong>Test the regular expression</strong></a></p><h4><strong>Example 1: Matching any lowercase vowel</strong></h4><pre><strong>vowelRegex = re.compile(r’[aeiou]’) <br></strong># r’(a|e|i|o|u’)</pre><h4><strong>Example 2: Matching letter in the alphabet</strong></h4><pre><strong>vowelRegex = re.compile(r’[a-z]’) # r’(a-z’) <br></strong># all lower case letters</pre><h4><strong>Example 3: Matching both lowercase &amp; uppercase vowels</strong></h4><p>Another example is the character class: <strong><em>[aeiouAEIOU]</em></strong>. This character class with match any vowel both lowercase and uppercase. Enter the following into the interactive shell:</p><pre># Finding vowels in string</pre><pre><strong>vowelRegex = re.compile(r’[aeiouAEIOU]’) # r’(a|e|i|o|u’)</strong></pre><pre><strong>vowelRegex.findall(‘Robocopy eats baby food’)</strong></pre><pre># return: [‘o’, ‘o’, ‘o’, ‘e’, ‘a’, ‘a’, ‘o’, ‘o’]</pre><p>You can also include ranges of letters or numbers by using a hyphen. For example, the character class <strong><em>[a-zA-Z0–9]</em></strong> will match all lowercase letters, uppercase letters, and numbers.</p><h4><strong>NOTE:</strong></h4><p>Inside the square brackets, the normal regex symbols are not interpreted as such. This means you do not need to escape the <strong>.</strong>, <strong>?</strong>, <strong>*</strong>, or <strong>()</strong> characters with a preceding backslash. For example, the character class <strong>[0–5.]</strong> will match digits 0 to 5 and a period. You do <strong>not </strong>need to write it as <strong>[0–5\.]</strong>.</p><h4><strong>Example 4: Matching Uppercase/Lowercase with Quantifier</strong></h4><pre><strong>doubleVowelRegex = re.compile(r’[aeiouAEIOU]{2}’)</strong> <br># two vowels in a row</pre><pre><strong>vowelRegex.findall(‘Robocopy eats baby food’)</strong></pre><pre># return: [‘ea’, ‘oo’]</pre><p>In the regex above, we’re looking for two vowels (lowercase/uppercase) in a row.</p><h3><strong>Negative Character Classes</strong></h3><pre><strong>consonantsRegex = re.compile(r’[^aeiouAEIOU]’)</strong> <br># match everything not specified in pattern</pre><pre><strong>consonantsRegex.findall(‘Robocop eats baby food.’)</strong></pre><pre># return: [‘R’, ‘b’, ‘c’, ‘p’, ‘ ‘, ‘t’, ‘s’, ‘ ‘, ‘b’, ‘b’, ‘y’, ‘ ‘, ‘f’, ‘d’, ‘.’]</pre><p>By placing a caret character <strong>(^)</strong> just after the character class’s opening bracket, you can make a<strong> negative character class</strong>. A <strong>negative character class </strong>will match all the characters that are <strong><em>not</em></strong> in the character class.</p><p>In the regex above, the pattern will match anything <strong>except</strong> the values in the character class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4b4d71d353a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/regular-expressions-character-classes-findall-method-c4b4d71d353a">Regular Expressions: Character Classes &amp; findall() Method</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regular Expressions: Repetition & Greedy / Non-Greedy Matching]]></title>
            <link>https://medium.com/swlh/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a3e570d3ae</guid>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 15:33:32 GMT</pubDate>
            <atom:updated>2020-08-26T22:27:26.105Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>If you’ve stumbled across this article and are new to this series of tutorials on regular expressions, feel free to take a look at the rest of the series (in order):</p><ol><li><a href="https://medium.com/@zohaibshahzadTO/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><p>Now that we have a decent understanding of what grouping is in regard to regex we can delve into more complicated concepts such as <strong>repetition operators</strong>.</p><p><strong>Repetition operators</strong> are special meta characters: <strong><em>? </em>(question mark)</strong>, <strong><em>* </em>(asterisk)</strong>, and <strong><em>+</em> (plus sign)</strong>. These repetition characters are used to specify how many times a sub-pattern can occur and they act differently in different situations.</p><h3><strong>The Question Mark (?)</strong></h3><p>In regex, the meta character “<strong><em>?</em></strong>” makes the preceding character optional. This symbol matches zero or one instance of the preceding character/group. For example, the regular expression <strong><em>[T]?he</em></strong> means: the uppercase letter ‘<strong>T</strong>’ is optional, which is then followed by the lowercase ‘<strong>h</strong>’ and ‘<strong>e</strong>’.</p><pre><strong>[T]he =&gt; The car is parked in the garage.</strong></pre><p><a href="https://regex101.com/r/RHEllP/1">Test the regular expression</a></p><pre><strong>[T]?he =&gt; The car is parked in the garage.</strong></pre><p><a href="https://regex101.com/r/oEyCe4/1">Test the regular expression</a></p><h4>Example 1: Question Mark Implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1689ea05b643a6595ed2341bc63d1b9e/href">https://medium.com/media/1689ea05b643a6595ed2341bc63d1b9e/href</a></iframe><p>Let’s explore the regex: <strong><em>Bat(wo)?man</em></strong>. It looks like we grouped (<strong><em>wo</em></strong>) together and a question mark (<strong><em>?</em></strong>) follows it which means that the group (<strong><em>wo</em></strong>) is optional (only zero or one).</p><p>If we analyze the string above, “<strong><em>The Adventures of Batman</em></strong>”, we can see that the regex pattern will match with “<strong><em>Batman</em></strong>” since the (<strong><em>wo</em></strong>) is optional.</p><h4>Example 2: Question Mark Implementation (con’t)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49ec9d8b28796838d7d6bc85e034964/href">https://medium.com/media/d49ec9d8b28796838d7d6bc85e034964/href</a></iframe><h4>Example 3: Question Mark Implementation (con’t)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b03886987aa65f58cb983da12c8aff8/href">https://medium.com/media/7b03886987aa65f58cb983da12c8aff8/href</a></iframe><p>For this string, “<strong><em>The Adventures of Batwowowowowoman</em></strong>”, the regex pattern will not match anything. The group (<strong><em>wo</em></strong>) repeats itself more than one time.</p><p>Going back to the telephone number example, if we want to make the area code optional this is what our regex pattern would look like:</p><pre><strong>phoneRegex = re.compile(r’(\d\d\d)-)?\d\d\d-\d\d\d\d’)</strong></pre><pre><strong>phoneRegex.search(‘My phone number is 415–555–1234. Call me tomorrow.’)</strong> # WORKS</pre><pre><strong>phoneRegex.search(‘My phone number is 555–1234. Call me tomorrow.’) </strong># WORKS</pre><h3>The Asterisk (*)</h3><p>The <strong><em>asterisks (*)</em></strong> matches zero or more repetitions of the preceding group/character. The regex, <strong><em>a*</em></strong>,<strong><em> </em></strong>means: zero or more repetitions of the preceding lowercase character ‘<strong><em>a</em></strong>’.</p><h4>Example 4: Implementing the asterisk</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3079c30ddffbe46e8ced19a07ab7ab38/href">https://medium.com/media/3079c30ddffbe46e8ced19a07ab7ab38/href</a></iframe><p>This example is one of the same from when we discussed the question mark repetition operator.</p><p>The regex: <strong><em>Bat(wo)*man</em></strong>. You can see that in front of the group (<strong><em>wo</em></strong>), there is an asterisk that follows it which means that there can be zero or more of the (<strong><em>wo</em></strong>) group in a string. The regex applied would be the correct fit for this given string.</p><h3><strong>The Addition Symbol (+)</strong></h3><p>The <strong><em>addition symbol (+)</em></strong> matches one or more repetitions of the preceding group/character. For example, the regular expression, <strong><em>c.+t</em></strong>, means: lowercase letter <strong><em>c</em></strong>, followed by at least one character, followed by the lowercase character <strong><em>t</em></strong>. It needs to be clarified that ‘<strong><em>t</em></strong>’ is the last ‘<strong><em>t</em></strong>’ in the sentence.</p><p>You’ll notice a period within the regex. The period is another special meta character which basically matches <strong><em>any single character </em></strong>except a line break <strong><em>(\n)</em></strong>.</p><pre><strong>c.+t =&gt; The fat cat sat on the mat</strong></pre><p><a href="https://regex101.com/r/IBXbSN/1">Test the regular expression</a></p><h4>Example 5: Implementing the Plus symbol</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10bcc1d96e70ec5ae83d6d8c61ff54f/href">https://medium.com/media/f10bcc1d96e70ec5ae83d6d8c61ff54f/href</a></iframe><h3><strong>Escaping ?, *, +</strong></h3><pre><strong>regex = re.compile(r’\+\*\?’)</strong></pre><pre><strong>regex.search(‘I learned about +*? regex syntax’)</strong></pre><p>If we want to escape any of the meta-characters such as <strong><em>?</em></strong>, <strong><em>*</em></strong> or <strong><em>+</em></strong>, we can simply place a <strong><em>backslash </em></strong>in front of them search for those characters.</p><pre><strong>regex = re.compile(r’(\+\*\?)+’)</strong></pre><pre><strong>regex.search(‘I learned about +*?+*?+*?+*?+*? regex syntax’)</strong></pre><p>In the regex above, we escaped the <strong><em>+</em></strong>, <strong><em>*</em></strong>, <strong><em>?</em></strong> meta characters and we’re looking for its literals. We’re matching the group, (<strong><em>\+\*\?</em></strong>), one or more times.</p><h3><strong>Repetition in Regex - Quantifiers</strong></h3><p>In regular expressions, braces are typically used as <strong>quantifiers </strong>to specify the number of times that a character or a group of characters can be repeated.</p><h4>Example 6: Quantifiers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b5935e0fce0a5ff7c88beac92d5e8c/href">https://medium.com/media/32b5935e0fce0a5ff7c88beac92d5e8c/href</a></iframe><p>Let’s take a look at the regex pattern above: <strong><em>(Ha){3}</em></strong>.</p><p>What we’re saying is, “match a string that repeats the group <strong><em>(Ha)</em></strong> 3 times”.</p><h4>Example 7: Quantifier’s (con’t)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bdee887e33502ffcdaf79aeb9fa5cb8/href">https://medium.com/media/3bdee887e33502ffcdaf79aeb9fa5cb8/href</a></iframe><p>In the regex above, we made the area code optional and specified we want to match <strong>3 phone numbers</strong> within the string.</p><h4><strong>Example 8: {x, y} - (at least x, at most y)</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8e56b438527224d7ac3a7552aa7ed9/href">https://medium.com/media/1f8e56b438527224d7ac3a7552aa7ed9/href</a></iframe><p>We can also match a range of possible repetitions <strong>{x, y} (at least x amount of times, and at most y amount of times)</strong></p><p>In the regex above, we’re matching for a minimum of <strong>(Ha)</strong> <strong>three times</strong> and searching up to a <strong>maximum of 5 times</strong>.</p><h4><strong>Example 9: {, 5} - Leaving off first number will be assumed as 0.</strong></h4><pre><strong>haRegex = re.compile(r’(Ha){,5}’)</strong></pre><p>Here we’re simply leaving off the first number. If we don’t specify the first number within the range, the interpreter will assume the range begins at 0. Hence, the range being<strong> 0–5</strong>.</p><h4><strong>Example 10: {3, } - Leaving off last number will assume the ending is indefinite</strong></h4><pre><strong>haRegex = re.compile(r’(Ha){3,}’)</strong></pre><p>Here we would assume that the range begins at 3 and the end is indefinite meaning the regex pattern looks for 3 or more.</p><h4><strong>Example 11: Implementing a Range</strong></h4><pre><strong>digitRegex = re.compile(r’(\d){3,5}’)</strong></pre><pre><strong>digitRegex.search(‘1234567890’)</strong></pre><p>In this regex, we’re basically looking for <strong>3–5 digits </strong>within a string.</p><h3><strong>A little note about Greedy and Non-Greedy Matching</strong></h3><p>Regular expressions begin matching <strong>immediately</strong>. The earliest match they can find is what it will return. By default, regular expressions do greedy matches. Greedy matches are essentially the longest possible strings that can be matched and returned according to the regex pattern.</p><h4><strong>Example 12: Non-Greedy Match</strong></h4><pre><strong>digitRegex = re.compile(r’(\d){3,5}?’)</strong></pre><pre><strong>digitRegex.search(‘1234567890’)</strong></pre><p>Let’s explore the regex above in more detail. If we place a question mark after the preceding range, the regex pattern will only traverse and match the minimum amount of repetitions and will not the maximum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a3e570d3ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae">Regular Expressions: Repetition &amp; Greedy / Non-Greedy Matching</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regular Expressions: Grouping and the Pipe Character]]></title>
            <link>https://medium.com/swlh/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78bff3d2b6</guid>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Tue, 05 May 2020 16:01:01 GMT</pubDate>
            <atom:updated>2020-08-26T22:28:48.227Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>If you’ve stumbled across this article and are new to this series of tutorials on regular expressions, feel free to take a look at the rest of the series (in order):</p><ol><li><a href="https://medium.com/@zohaibshahzadTO/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><p>In this tutorial, we’ll be delving into grouping and the <strong>pipe character</strong> specifically for regex.</p><p>In the previous article, we worked on a scenario where we would create a function and then soon after a regular expression to search for patterns matching telephone numbers within any string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100ddd353a691beb25cc1351535a7631/href">https://medium.com/media/100ddd353a691beb25cc1351535a7631/href</a></iframe><p>The snippet of code above is what we concluded the previous article with. However, what if we just wanted the area code or just some part of the phone number? That’s where grouping comes into play; we can use parentheses to mark out the groups.</p><h3>Groups in Regex</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68cb8efdb469bdc7cdcd081cb0f10b9b/href">https://medium.com/media/68cb8efdb469bdc7cdcd081cb0f10b9b/href</a></iframe><p>Take a look at <strong><em>line 1</em></strong>. You’ll notice we wrapped parentheses around the area code and another set of parentheses around the rest of the digits.</p><p>As you can see, we have two groups within the regex pattern. The<strong> first group </strong>is for the area code while the<strong> second group</strong> is for the rest of the phone number. Now if we want to search for just the area code, we can call that group out specifically. We’re simply matching a portion of the phone number using what is known as a capturing group.</p><p>What if we want to literally find brackets within the pattern?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/566f825ac1f133e4a598355ee92d8d60/href">https://medium.com/media/566f825ac1f133e4a598355ee92d8d60/href</a></iframe><p>Directing your attention to <strong><em>line 1</em></strong> in the snippet of code above. Notice how we placed a <strong>backslash in front of the opening bracket</strong> and <strong>another backslash in front of the closing bracket</strong>. That’s how we would <strong>escape parentheses</strong> in regex and that’s how we can search for <strong>literal parentheses</strong> in our regex pattern.</p><h4><strong>NOTE:</strong></h4><p><strong>\(and\) </strong>matches literal parentheses in the regex string</p><h3><strong>Backslashes in Regex</strong></h3><p>The backslash is an escape character in strings for any programming language. That means the backslash has a predefined meaning in languages like Python or Java. You have to use a double backslash to define a single backslash. If you want to define <strong><em>\w</em></strong>, then you must be using <strong><em>\w</em></strong> in your regex. If you want to use a backslash as a literal, you must type<strong><em> \\</em></strong> as <strong><em>\</em></strong> is also an escape character in regular expressions.</p><h3><strong>The Pipe Character</strong></h3><p>The <strong>pipe character</strong> also referred to as the vertical bar indicates alternation, that is, a given choice of alternatives. Most programmers know what a pipe character is and how it works from working with simple <strong><em>if statements</em></strong>. Pipe characters work the same in regular expressions.</p><p>Let’s take a look at the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1647ab4b4e0974534f45b87e5babe7a/href">https://medium.com/media/b1647ab4b4e0974534f45b87e5babe7a/href</a></iframe><p>Looking at <strong><em>line 1</em></strong> of the code. You’ll see we begin the regex pattern by searching for a string that begins with <strong><em>Bat </em></strong>and then following that are given alternatives: <strong><em>man</em></strong>, <strong><em>mobile</em></strong>, <strong><em>copter</em></strong>, and <strong><em>bat</em></strong>.</p><p>That regex pattern is simply saying: “find me a string that starts with <strong><em>Bat </em></strong>and any of the texts attached to the <strong><em>Bat </em></strong>prefix are acceptable”.</p><p>The following would be match-able strings: <strong><em>Batman</em></strong>, <strong><em>Batmobile</em></strong>, <strong><em>Batcopter</em></strong>, <strong><em>Batbat</em></strong>.</p><pre><strong>mo = batRegex.search(‘Batmotorcycle lost a wheel’)</strong></pre><pre><strong>mo == None </strong># returns value “none”</pre><p>Now if we tried searching for a match in the string above, we wouldn’t get one.</p><p>If the <strong><em>search()</em></strong> method cannot find the pattern specified, it will return a value called “<strong>None</strong>”. If we blindly assign whatever the <strong><em>search()</em></strong> method returns to a match object (<strong><em>mo</em></strong>) and call the <strong><em>group()</em></strong> method on it, you’ll get an error message because the “<strong>None</strong>” value does not have a method called <strong><em>group()</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78bff3d2b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6">Regular Expressions: Grouping and the Pipe Character</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pattern Matching with Regular Expressions]]></title>
            <link>https://medium.com/swlh/pattern-matching-with-regular-expressions-45442567b5d4?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/45442567b5d4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Mon, 04 May 2020 15:01:01 GMT</pubDate>
            <atom:updated>2025-04-13T04:36:11.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>A series of tutorials on Regular Expressions using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwNPrfyimdsgjIW0iX-5VQ.jpeg" /></figure><p>This article is the first in a series of tutorials where we will demonstrate how you can use/implement regular expressions for text pattern matching, validation, parsing/replacing strings, passing through translating data to other formats, web scraping, etc. The following are the tutorials in order:</p><ol><li><a href="https://medium.com/@zohaibshahzadTO/pattern-matching-with-regular-expressions-45442567b5d4"><strong>Regular Expressions: Basics</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-grouping-and-the-pipe-character-d78bff3d2b6"><strong>Regular Expressions: Grouping &amp; the Pipe Character</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-repetition-greedy-non-greedy-matching-40a3e570d3ae"><strong>Regular Expressions: Repetition &amp; Greedy/Non-Greedy Matching</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-character-classes-findall-method-c4b4d71d353a"><strong>Regular Expressions: Character Classes &amp; findall() Method</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-dot-star-and-the-caret-dollar-characters-5458c52ad2a9"><strong>Regular Expressions: Dot-Star and the Caret/Dollar Characters</strong></a></li><li><a href="https://medium.com/@zohaibshahzadTO/regular-expressions-sub-method-and-verbose-mode-1902cbc0ceef"><strong>Regular Expressions: sub() Method and Verbose Mode</strong></a></li></ol><p>Before I even get into what a regular expression is or “regex” for short, I think its better I start this lesson out with an example. I want to start off by creating a function that checks if the input is a phone number. For simplicity purposes, the phone number format we’ll be referring to are US/Canada based.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53c07f88d09b1019b08589c25706c873/href">https://medium.com/media/53c07f88d09b1019b08589c25706c873/href</a></iframe><p>Now this function seems to work and can detect whether the input is a phone number. But maybe we want to take a string and search for whether there’s a phone number embedded within it and print it out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa1325701d69722b79634b90f15690d/href">https://medium.com/media/eaa1325701d69722b79634b90f15690d/href</a></iframe><p>In this snippet of code, we wanted to search for phone number within strings. We first loop though the length of the “message” string and slice the message from 0–12 characters and store that in the “chunk” variable. We then check if that chunk matches a phone number and if not, we gradually shift that chunk and iterate through the string until we get a string between the 0–12 characters that match a phone number.</p><p>Now this is a lot of code to just check if an input or a string contains a phone number. There’s always an easier way and that’s where regular expressions or “regex” come into play.</p><h3><strong>What are Regular Expressions?</strong></h3><p>Regular expressions are specially encoded text strings used as patterns for matching sets of strings. Some have even called them wildcards on steroids. Knowing how to apply regular expressions is powerful. At some point in your career as a developer, you’ll find yourself working on a program where you’ll need to extract information from some text by searching for one or more matches of a specific search pattern (i.e. a specific sequence of ASCII or unicode characters) and regex can save you time and make your code more efficient.</p><p>Other applications using regex include validation, parsing/replacing strings, passing through translating data to other formats and web scraping. In addition, the syntax of regex is largely the same for all programming languages (with some minor distinctions).</p><p>We’ll be using Python throughout this series of regex tutorials. Since we’re using Python, what we’ll want to do is import a built-in Python module called <strong><em>re</em></strong> (‘re’ referring to ‘regular expressions’), Importing that module will enable us to start working with regex.</p><h4><strong>NOTE:</strong> <strong>Python Modules</strong></h4><p>Built-in modules are written in C and integrated with the Python interpreter. Each built-in module contains resources for certain system-specific functionalities such as OS management, disk IO, etc.</p><p>In Python, each built-in module comes with its own methods. Since we’re importing the regex module (<strong><em>re</em></strong>), it’s important you know what each method does beforehand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8fUGQATTnazfMnCQJeyBEA.png" /></figure><p>Regex has a reputation for being clustered and messy with all the symbols and special characters, but it really depends on how you approach it. There’s a natural progression that looks something as simple as this:</p><pre><strong>\d</strong> (represent a digits between 0-9)</pre><p>to something a bit more complicated like this:</p><pre><strong>^(\(\d{3}\)|^\d{3}[.-]?)?\d{3}[.-]?\d{4}$</strong></pre><p>which is where we’ll end up after this series of regex tutorials. It’s a fairly robust regular expression that matches a 10 digit, North American telephone number.</p><h3>Text Pattern Recognition Using Regex Makes It Easier</h3><p>Let’s re-write the<strong><em> isPhoneNumber.py</em></strong> function and redo the task using regex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100ddd353a691beb25cc1351535a7631/href">https://medium.com/media/100ddd353a691beb25cc1351535a7631/href</a></iframe><p>Let’s break this snippet of code down one line at a time. First, we imported the <strong><em>re</em></strong> module that enables us to work with regular expressions. Second, we simply created a short string containing phone numbers we want to search and analyze through it, and stored it in a variable called “message”.</p><p>Now we’re going to be using a method from the<strong><em> re</em></strong> module. <strong><em>Re.compile()</em></strong> allows to create the actual regular expression (special text used as patterns for matching sets of strings).</p><pre><strong>re.compile(r’\d\d\d-\d\d\d-\d\d\d\d’)</strong></pre><p>Typically before we create our regular expression, we’re working with the following at first: re.compile(r’ ’)</p><p>The <strong><em>r’ ’</em></strong> is called a <strong>raw string</strong> and in Python its what we place our regex pattern within. For now, all you need to know is that the regular expression is inserted within that raw string.</p><p>Within the snippet of code, you’ll see a bunch of <strong><em>\d</em></strong> jumbled together. The<strong><em> \d </em></strong>is a character shorthand which by itself will match any numeric digit character between 0–9.</p><p>You can see that we’re repeating <strong><em>\d</em></strong> three and four times in sequence which will actually match the same pattern a North American phone number follows. The hyphens within the regex are entered as literal characters and will be matched as such.</p><p>After crafting our regex pattern, we’ll store that pattern into a variable called <strong><em>phoneNumRegex</em></strong>. We’ll then store <strong><em>phoneNumRegex </em></strong>into <strong><em>mo</em></strong> which is a special variable that returns the matched object. We then use a method called <strong><em>group()</em></strong>. The matched objects have a group method which tells you the actual text found. All these regex methods are included within the <strong><em>re </em></strong>module.</p><h4><strong>DETOUR:</strong></h4><p>Take a look at <strong>line 5</strong> in the code snippet. If you want to find all occurrences of a phone number within the <strong><em>message </em></strong>string. You can use the <strong><em>findall()</em></strong> method. Your code would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7685db49fb9f9a5e4794aef0d35985e/href">https://medium.com/media/f7685db49fb9f9a5e4794aef0d35985e/href</a></iframe><h3>Credits</h3><p>First, I’d like to credit these series of articles for RegEx to <strong><em>Al Sweigart.</em></strong> I’m essentially basing this RegEx series on his online book called: <strong><em>Automate the Boring Stuff with Python </em></strong>(link below). And I’d say a vast majority of the examples in these articles are from <strong><em>Automate the Boring Stuff with Python</em></strong>. Please check that book out, its amazing.</p><h3>Resources</h3><h4><strong>Automate the Boring Stuff with Python</strong></h4><p>Big shout out to <strong>Al Sweigart</strong>. He has a course on U<a href="https://www.udemy.com/course/automate/">demy</a> and a free book online called: <strong>Automate the Boring Stuff with Python</strong>.</p><p><a href="http://automatetheboringstuff.com/2e/"><strong>http://automatetheboringstuff.com/2e/</strong></a></p><p>In his course, he has a section on Regular Expressions (chapter 7) which I personally found to be a good refresher.</p><h4>Regex One</h4><p>Feel free to check out this link as well as it does a decent job at walking you through the different components of Regex.</p><p><a href="https://regexone.com/"><strong>https://regexone.com/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45442567b5d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/pattern-matching-with-regular-expressions-45442567b5d4">Pattern Matching with Regular Expressions</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Walkthrough: LeetCode 66]]></title>
            <link>https://medium.com/@zohaibshahzadTO/the-walkthrough-leetcode-66-dc33b5fe0641?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc33b5fe0641</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 17:01:01 GMT</pubDate>
            <atom:updated>2020-01-23T17:01:01.313Z</atom:updated>
            <content:encoded><![CDATA[<p>LeetCode 66: Plus One</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*USrPk-jA_RD8HVa8RsFX2g.png" /></figure><p>If we’re given as an array the integer ‘123’, we simply want to increment the last digit and return the corresponding array representing that integer.</p><p>The first thing that should be pointed out is that we want to iterate via the given array backwards. A couple of edge cases that should be discussed is if the last digit of the number is ‘9’.</p><p>If we’re to encounter a case where the last digit of an integer value is ‘9’, then we set that index value to zero and then continue iterating. If not, then we’re working with a case where the last digit is anything but ‘9’ and in that case we simply increment that value of the digit and return the array of that integer.</p><p>Now if the last digits is a ‘9’. We simply set that digit to 0. The <strong><em>for loop</em></strong> will continue setting digits to ‘0’ if they’re ‘9’ and eventually will return the array. However, if we don’t return the array, that means we would have been dealing with a number that was for example: <strong>9</strong>, <strong>99</strong>,<strong> 999</strong>, <strong>9999</strong>, etc. In that case, the array returned will contains all 0’s. The <strong><em>for loop</em></strong> will break in that case. We need to resize the array in that case.</p><p><strong>Example:</strong> If we have 99, we return 100 which includes an extra digit.</p><p>When using languages like Java, we’ll have to resize the array if we’re to increment the last digit ‘9’</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8529f7447e43713d8097f42bc43f99c/href">https://medium.com/media/b8529f7447e43713d8097f42bc43f99c/href</a></iframe><p>Taking a look at <strong><em>line 9 </em></strong>above<strong><em>, </em></strong>that’s where we re-size the array if the last digit of the integer value is ‘9’. <strong>[digits.length + 1]</strong> basically says before our integer was ‘99’ and by adding an extra digit length to it, it now becomes ‘100’. We add one digit size to the array which then sets all values in the array to ‘0’ by default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa1aec471e17d9367b64199d8b4fee2/href">https://medium.com/media/6aa1aec471e17d9367b64199d8b4fee2/href</a></iframe><p>Direct your attention to <strong><em>line 11</em></strong>. <strong><em>Line 11</em></strong> would be how we re-size the array in Javascript. Destructuring array’s have many benefits and but destructuring as a whole is an article for another day. <strong>[1, …digits]</strong> basically says we’re inserting a digit value of ‘1’ in front of whatever the rest of the integer value is.</p><p><strong>Example:</strong> If we were dealing with<strong> [9, 9]</strong>, we would end up increasing each digit value to <strong>[0, 0]</strong>. We would then add another placeholder of 1 to the beginning: <strong>[1, 0, 0]</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc33b5fe0641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Walkthrough: LeetCode 1]]></title>
            <link>https://medium.com/@zohaibshahzadTO/the-walkthrough-leetcode-1-6dba9588235d?source=rss-bbde1faf3db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dba9588235d</guid>
            <dc:creator><![CDATA[Zohaib Shahzad]]></dc:creator>
            <pubDate>Fri, 17 Jan 2020 16:01:01 GMT</pubDate>
            <atom:updated>2020-01-20T21:01:19.557Z</atom:updated>
            <content:encoded><![CDATA[<p>LeetCode 1: Two Sum</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5yts7LtM702xhoGbZFTE0A.png" /></figure><p>Let’s start with the example given in the LeetCode problem. Suppose we’re given the array [2, 7, 11, 18] and a target value of 9. We’re tasked with finding two number within the array that add up to the target and then return the indices of those respective number.</p><h3><strong>Approach #1: Brute Force (Naive)</strong></h3><p>The naive approach typically involves using two nested <strong><em>for loops</em></strong>. How would we use them to solve the problem? Begin by iterating via the array starting with the zero index and we’ll have another <strong><em>for loop</em></strong> nested within which starts with the first index (j = i + 1). We’ll iterate through the rest of array and for every value within that array, we’ll check if any of those values is the complement to the value in the zero index.</p><p><strong>Key:</strong> loop via each element (x) and if there is another value that equals to (target — x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mqpZBX5yo2otxBmZRWiCNw.png" /><figcaption><strong>Figure 1:</strong> Having ‘j’ start at index 1, we have it iterate via the rest of the array and check if any of those values is the complement to the value where index ‘i’ is pointing to. If it is, then nums[i] + nums[j] = target. If not, then increment the ‘i’ pointer by 1 and then run through the 2nd <em>for loop</em> again, etc.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e4dd95afeff8a9526e2d8396c91761/href">https://medium.com/media/c0e4dd95afeff8a9526e2d8396c91761/href</a></iframe><p><strong>Time Complexity: O(n²)</strong> — For each element, we try to find its complement by looping via the rest of the array which takes O(n) time</p><p><strong>Space Complexity: O(1)</strong></p><h3><strong>Approach #2: Two Pass Hash Table</strong></h3><p>When talking about a more real world and optimal solution, a brute force solution just doesn’t cut it.</p><p>This is where data structures come into play.</p><p>In order to improve our run-time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. Writing an algorithm with nested for-loops is a no no at this point. The best way to maintain a mapping of each element in the array to its index? A hash table.</p><p>Implementing a hash table can reduce the look-up time from O(n) to O(1) by trading space for speed.</p><p>A hash table is built recently for this purpose, it supports fast look up in near constant time. We say “near” constant time because if a collision occurred, a lookup could be degenerated to O(n) time. However, lookup’s in hash tables should be amortized O(1) as long as the hash table was chosen carefully.</p><p>A simple implementation uses two iterations of the array. In the first iteration, we add each elements value and its index to the table (which makes sense because hash table accept key-value pairs (K, V)). In the second iteration we then check if each element’s complement (target — nums[i]) exists in the same.</p><p><strong>NOTE:</strong> the complement must not be nums[i] itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*A_JzS14uiQq-gK-yBAUVUQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12a93317070f67163ca81fda5b57622/href">https://medium.com/media/f12a93317070f67163ca81fda5b57622/href</a></iframe><p><strong>Time Complexity: O(n) — </strong>each lookup cost only O(1)</p><p><strong>Space Complexity: O(n)</strong></p><h3><strong>Approach #3: One Pass Hash Table</strong></h3><p>As the approach suggests, this solution will implement a one pass hash table. While we iterate through the array and insert the elements into the table, we can also look back to check if the current element’s complement already exists in the table. If it exists, we have found a solution and return it immediately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c2eab5efa56a4bd306ee10180f328b/href">https://medium.com/media/e2c2eab5efa56a4bd306ee10180f328b/href</a></iframe><p><strong>Time Complexity: O(n)</strong> — traverses list iterating<strong><em> n</em></strong> elements only once. Each lookup is O(1) constant time.</p><p><strong>Space Complexity: O(n)</strong> — Extra space required depends on the number of items in the hash table which stores at most, <strong><em>n</em></strong> elements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dba9588235d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>