Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Re ? Quantifier

#1
Python Re ? Quantifier

<div><p>Congratulations, you’re about to learn one of the most frequently used regex operators: the question mark quantifier <strong>A?</strong>. </p>
<p>In particular, this article is all about the <strong>? quantifier in Python’s <a rel="noreferrer noopener" target="_blank" href="https://docs.python.org/3/library/re.html">re library</a>. </strong></p>
<h2>What’s the Python Re ? Quantifier</h2>
<p>When applied to regular expression <strong>A</strong>, Python’s <strong>A?</strong> quantifier matches either zero or one occurrences of <strong>A</strong>. The ? quantifier always applies only to the preceding regular expression. For example, the regular expression <strong>‘hey?’</strong> matches both strings <strong>‘he’ </strong>and <strong>‘hey’</strong>. But it does not match the empty string because the ? quantifier does not apply to the whole regex ‘hey’ but only to the preceding regex ‘y’. </p>
<p>Let’s study two basic examples to help you gain a deeper understanding. Do you get all of them?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>>
>>> re.findall('aa[cde]?', 'aacde aa aadcde')
['aac', 'aa', 'aad']
>>>
>>> re.findall('aa?', 'accccacccac')
['a', 'a', 'a']
>>>
>>> re.findall('[cd]?[cde]?', 'ccc dd ee')
['cc', 'c', '', 'dd', '', 'e', 'e', '']</pre>
<p>Don’t worry if you had problems understanding those examples. You’ll learn about them next. Here’s the first example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> re.findall('aa[cde]?', 'aacde aa aadcde')
['aac', 'aa', 'aad']</pre>
<p>You use the re.findall() method. In case you don’t know it, here’s the definition from the <a href="https://blog.finxter.com/python-re-findall/">Finxter blog article</a>:</p>
<p><strong>The re.findall(pattern, string) method finds all occurrences of the pattern in the string and returns a list of all matching substrings.</strong></p>
<p><a href="https://blog.finxter.com/python-re-findall/">Please consult the blog article to learn everything you need to know about this fundamental Python method.</a></p>
<p>The first argument is the regular expression pattern <strong>‘aa[cde]?’</strong>. The second argument is the string to be searched for the pattern. In plain English, you want to find all patterns that start with two ‘a’ characters, followed by one optional character—which can be either ‘c’, ‘d’, or ‘e’. </p>
<p>The findall() method returns three matching substrings:</p>
<ul>
<li>First, string ‘aac’ matches the pattern. After Python consumes the matched substring, the remaining substring is ‘de aa aadcde’. </li>
<li>Second, string ‘aa’ matches the pattern. Python consumes it which leads to the remaining substring ‘ aadcde’.</li>
<li>Third, string ‘aad’ matches the pattern in the remaining substring. What remains is ‘cde’ which doesn’t contain a matching substring anymore.</li>
</ul>
<p>The second example is the following:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> re.findall('aa?', 'accccacccac')
['a', 'a', 'a']</pre>
<p>In this example, you’re looking at the simple pattern ‘aa?’. You want to find all occurrences of character ‘a’ followed by an optional second ‘a’. But be aware that the optional second ‘a’ is not needed for the pattern to match.</p>
<p>Therefore, the regex engine finds three matches: the characters ‘a’. </p>
<p>The third example is the following:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> re.findall('[cd]?[cde]?', 'ccc dd ee')
['cc', 'c', '', 'dd', '', 'e', 'e', '']</pre>
<p>This regex pattern looks complicated: ‘[cd]?[cde]?’. But is it really?</p>
<p>Let’s break it down step-by-step:</p>
<p>The first part of the regex [cd]? defines a character class [cd] which reads as “match either c or d”. The question mark quantifier indicates that you want to match either one or zero occurrences of this pattern. </p>
<p>The second part of the regex [cde]? defines a character class [cde] which reads as “match either c, d, or e”. Again, the question mark indicates the zero-or-one matching requirement. </p>
<p>As both parts are optional, the empty string matches the regex pattern. However, the Python regex engine attempts <em>as much as possible</em>. </p>
<p>Thus, the regex engine performs the following steps:</p>
<ul>
<li>The first match in the string ‘ccc dd ee’ is ‘cc’. The regex engine consumes the matched substring, so the string ‘c dd ee’ remains.</li>
<li>The second match in the remaining string is the character ‘c’. The empty space ‘ ‘ does not match the regex so the second part of the regex [cde] does not match. Because of the question mark quantifier, this is okay for the regex engine. The remaining string is ‘ dd ee’.</li>
<li>The third match is the empty string ”. Of course, Python does not attempt to match the same position twice. Thus, it moves on to process the remaining string ‘dd ee’. </li>
<li>The fourth match is the string ‘dd’. The remaining string is ‘ ee’.</li>
<li>The fifth match is the string ”. The remaining string is ‘ee’.</li>
<li>The sixth match is the string ‘e’. The remaining string is ‘e’.</li>
<li>The seventh match is the string ‘e’. The remaining string is ”.</li>
<li>The eighth match is the string ”. Nothing remains.</li>
</ul>
<p>This was the most complicated of our examples. Congratulations if you understood it completely! </p>
<h2>[Collection] What Are The Different Python Re Quantifiers?</h2>
<p>The question mark quantifier—Python re ?—is only one of many regex operators. If you want to use (and understand) regular expressions in practice, you’ll need to know all of them by heart!</p>
<p>So let’s dive into the other operators:</p>
<p>A regular expression is a decades-old concept in computer science. Invented in the 1950s by famous mathematician Stephen Cole Kleene, the decades of evolution brought a huge variety of operations. Collecting all operations and writing up a comprehensive list would result in a very thick and unreadable book by itself.</p>
<p>Fortunately, you don’t have to learn all regular expressions before you can start using them in your practical code projects. Next, you’ll get a quick and dirty overview of the most important regex operations and how to use them in Python. In follow-up chapters, you’ll then study them in detail — with many practical applications and code puzzles.</p>
<p>Here are the most important regex quantifiers:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Quantifier</strong></td>
<td><strong>Description</strong></td>
<td><strong>Example</strong></td>
</tr>
<tr>
<td><code>.</code></td>
<td>The <strong>wild-card</strong> (‘dot’) matches any character in a string except the newline character ‘\n’.</td>
<td>Regex ‘…’ matches all words with three characters such as ‘abc’, ‘cat’, and ‘dog’.</td>
</tr>
<tr>
<td><code>*</code></td>
<td>The <strong>zero-or-more</strong> asterisk matches an arbitrary number of occurrences (including zero occurrences) of the immediately preceding regex.</td>
<td>Regex ‘cat*’ matches the strings ‘ca’, ‘cat’, ‘catt’, ‘cattt’, and ‘catttttttt’.</td>
</tr>
<tr>
<td><code>?</code></td>
<td>The <strong>zero-or-one</strong> matches (as the name suggests) either zero or one occurrences of the immediately preceding regex. </td>
<td>Regex ‘cat?’ matches both strings ‘ca’ and ‘cat’ — but not ‘catt’, ‘cattt’, and ‘catttttttt’.</td>
</tr>
<tr>
<td><code>+</code></td>
<td>The <strong>at-least-one</strong> matches one or more occurrences of the immediately preceding regex. </td>
<td>Regex ‘cat+’ does not match the string ‘ca’ but matches all strings with at least one trailing character ‘t’ such as ‘cat’, ‘catt’, and ‘cattt’.</td>
</tr>
<tr>
<td><code>^</code></td>
<td>The <strong>start-of-string</strong> matches the beginning of a string. </td>
<td>Regex ‘^p’ matches the strings ‘python’ and ‘programming’ but not ‘lisp’ and ‘spying’ where the character ‘p’ does not occur at the start of the string.</td>
</tr>
<tr>
<td><code>$</code></td>
<td>The <strong>end-of-string</strong> matches the end of a string. </td>
<td>Regex ‘py$’ would match the strings ‘main.py’ and ‘pypy’ but not the strings ‘python’ and ‘pypi’.</td>
</tr>
<tr>
<td><code>A|B</code></td>
<td>The <strong>OR</strong> matches either the regex A or the regex B. Note that the intuition is quite different from the standard interpretation of the or operator that can also satisfy both conditions. </td>
<td>Regex ‘(hello)|(hi)’ matches strings ‘hello world’ and ‘hi python’. It wouldn’t make sense to try to match both of them at the same time.</td>
</tr>
<tr>
<td><code>AB</code></td>
<td> The <strong>AND</strong> matches first the regex A and second the regex B, in this sequence. </td>
<td>We’ve already seen it trivially in the regex ‘ca’ that matches first regex ‘c’ and second regex ‘a’.</td>
</tr>
</tbody>
</table>
</figure>
<p>Note that I gave the above operators some more meaningful names (in bold) so that you can immediately grasp the purpose of each regex. For example, the ‘^’ operator is usually denoted as the ‘caret’ operator. Those names are not descriptive so I came up with more kindergarten-like words such as the “start-of-string” operator.</p>
<p>We’ve already seen many examples but let’s dive into even more!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re text = ''' Ha! let me see her: out, alas! he's cold: Her blood is settled, and her joints are stiff; Life and these lips have long been separated: Death lies on her like an untimely frost Upon the sweetest flower of all the field. ''' print(re.findall('.a!', text)) '''
Finds all occurrences of an arbitrary character that is
followed by the character sequence 'a!'.
['Ha!'] ''' print(re.findall('is.*and', text)) '''
Finds all occurrences of the word 'is',
followed by an arbitrary number of characters
and the word 'and'.
['is settled, and'] ''' print(re.findall('her:?', text)) '''
Finds all occurrences of the word 'her',
followed by zero or one occurrences of the colon ':'.
['her:', 'her', 'her'] ''' print(re.findall('her:+', text)) '''
Finds all occurrences of the word 'her',
followed by one or more occurrences of the colon ':'.
['her:'] ''' print(re.findall('^Ha.*', text)) '''
Finds all occurrences where the string starts with
the character sequence 'Ha', followed by an arbitrary
number of characters except for the new-line character. Can you figure out why Python doesn't find any?
[] ''' print(re.findall('\n$', text)) '''
Finds all occurrences where the new-line character '\n'
occurs at the end of the string.
['\n'] ''' print(re.findall('(Life|Death)', text)) '''
Finds all occurrences of either the word 'Life' or the
word 'Death'.
['Life', 'Death'] '''
</pre>
<p>In these examples, you’ve already seen the special symbol ‘\n’ which denotes the new-line character in Python (and most other languages). There are many special characters, specifically designed for regular expressions. Next, we’ll discover the most important special symbols.</p>
<h2>What’s the Difference Between Python Re ? and * Quantifiers?</h2>
<p>You can read the Python Re A? quantifier as <strong>zero-or-one regex</strong>: the preceding regex A is matched either zero times or exactly once. But it’s not matched more often.</p>
<p>Analogously, you can read the Python Re A* operator as the <strong>zero-or-multiple-times regex</strong> (I know it sounds a bit clunky): the preceding regex A is matched an arbitrary number of times.</p>
<p>Here’s an example that shows the difference:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> re.findall('ab?', 'abbbbbbb')
['ab']
>>> re.findall('ab*', 'abbbbbbb')
['abbbbbbb']</pre>
<p>The regex ‘ab?’ matches the character ‘a’ in the string, followed by character ‘b’ if it exists (which it does in the code). </p>
<p>The regex ‘ab*’ matches the character ‘a’ in the string, followed by as many characters ‘b’ as possible.</p>
<h2>What’s the Difference Between Python Re ? and + Quantifiers?</h2>
<p>You can read the Python Re A? quantifier as <strong>zero-or-one regex</strong>: the preceding regex A is matched either zero times or exactly once. But it’s not matched more often.</p>
<p>Analogously, you can read the Python Re A+ operator as the <strong>at-least-once regex</strong>: the preceding regex A is matched an arbitrary number of times but at least once.</p>
<p>Here’s an example that shows the difference:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> re.findall('ab?', 'aaaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> re.findall('ab+', 'aaaaaaaa')
[]</pre>
<p>The regex ‘ab?’ matches the character ‘a’ in the string, followed by character ‘b’ if it exists—but it doesn’t in the code. </p>
<p>The regex ‘ab+’ matches the character ‘a’ in the string, followed by as many characters ‘b’ as possible—but at least one. However, the character ‘b’ does not exist so there’s no match.</p>
<h2>What are Python Re <code>*?</code>, <code>+?</code>, <code>??</code> Quantifiers?</h2>
<p>You’ve learned about the three quantifiers:</p>
<ul>
<li>The quantifier A* matches an arbitrary number of patterns A.</li>
<li>The quantifier A+ matches at least one pattern A.</li>
<li>The quantifier A? matches zero-or-one pattern A.</li>
</ul>
<p>Those three are all <strong>greedy</strong>: they match as many occurrences of the pattern as possible. Here’s an example that shows their greediness:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> re.findall('a*', 'aaaaaaa')
['aaaaaaa', '']
>>> re.findall('a+', 'aaaaaaa')
['aaaaaaa']
>>> re.findall('a?', 'aaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a', '']</pre>
<p>The code shows that all three quantifiers *, +, and ? match as many ‘a’ characters as possible.</p>
<p>So, the logical question is: how to match as few as possible? We call this <strong>non-greedy </strong>matching. You can append the question mark after the respective quantifiers to tell the regex engine that you intend to match as few patterns as possible: *?, +?, and ??.</p>
<p>Here’s the same example but with the non-greedy quantifiers:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> re.findall('a*?', 'aaaaaaa')
['', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '']
>>> re.findall('a+?', 'aaaaaaa')
['a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> re.findall('a??', 'aaaaaaa')
['', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '', 'a', '']</pre>
<p>In this case, the code shows that all three quantifiers *?, +?, and ?? match as few ‘a’ characters as possible. </p>
<h2>Related Re Methods</h2>
<p>There are five important regular expression methods which you should master:</p>
<ul>
<li>The <strong>re.findall(pattern, string)</strong> method returns a list of string matches. Read more in <a href="https://blog.finxter.com/python-re-findall/">our blog tutorial</a>.</li>
<li>The <strong>re.search(pattern, string)</strong> method returns a match object of the first match. Read more in <a href="https://blog.finxter.com/python-regex-search/">our blog tutorial</a>.</li>
<li>The <strong>re.match(pattern, string)</strong> method returns a match object if the regex matches at the beginning of the string. Read more in <a href="https://blog.finxter.com/python-regex-match/">our blog tutorial</a>.</li>
<li>The <strong>re.fullmatch(pattern, string)</strong> method returns a match object if the regex matches the whole string. Read more in <a href="https://blog.finxter.com/python-regex-fullmatch/">our blog tutorial</a>.</li>
<li>The <strong>re.compile(pattern)</strong> method prepares the regular expression pattern—and returns a regex object which you can use multiple times in your code. Read more in <a href="https://blog.finxter.com/python-regex-compile/">our blog tutorial</a>.</li>
<li>The<strong> re.split(pattern, string)</strong> method returns a list of strings by matching all occurrences of the pattern in the string and dividing the string along those. Read more in <a href="https://blog.finxter.com/python-regex-split/">our blog tutorial</a>.</li>
<li>The <strong>re.sub(The re.sub(pattern, repl, string, count=0, flags=0)</strong> method returns a new string where all occurrences of the pattern in the old string are replaced by repl. Read more in <a href="https://blog.finxter.com/python-regex-sub/">our blog tutorial</a>.</li>
</ul>
<p>These seven methods are 80% of what you need to know to get started with Python’s regular expression functionality.</p>
<h2>Where to Go From Here?</h2>
<p>You’ve learned everything you need to know about the question mark quantifier ? in this regex tutorial. </p>
<p><em><strong>Summary</strong>: When applied to regular expression A, Python’s A? quantifier matches either zero or one occurrences of A. The ? quantifier always applies only to the preceding regular expression. For example, the regular expression ‘hey?’ matches both strings ‘he’ and ‘hey’. But it does not match the empty string because the ? quantifier does not apply to the whole regex ‘hey’ but only to the preceding regex ‘y’.</em></p>
<p><strong>Want to earn money while you learn Python?</strong> Average Python programmers earn more than $50 per hour. You can certainly become average, can’t you?</p>
<p>Join the free webinar that shows you how to become a thriving coding business owner online!</p>
<p><a href="https://blog.finxter.com/subscribe/">[Webinar] Become a Six-Figure Freelance Developer with Python</a></p>
<p>Join us. It’s fun! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>


https://www.sickgaming.net/blog/2020/01/...uantifier/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016