Sick Gaming
[Tut] What are Regular Expressions Used For? 10 Applications - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] What are Regular Expressions Used For? 10 Applications (/thread-93851.html)



[Tut] What are Regular Expressions Used For? 10 Applications - xSicKxBot - 03-04-2020

What are Regular Expressions Used For? 10 Applications

<div><p>The web is full of <a rel="noreferrer noopener" aria-label="tutorials (opens in a new tab)" href="https://blog.finxter.com/python-regex/" target="_blank">tutorials</a> about regular expressions. But I realized that most of those tutorials lack a thorough motivation. </p>
<ul>
<li>Why do regular expressions exist? </li>
<li>What are they used for? </li>
<li>What are some practical applications?</li>
</ul>
<p>Somehow, the writers of those tutorials believe that readers are motivated by default to learn a technology that’s complicated and hard to learn. </p>
<p>Well, readers are not. If you’re like me, you tend to avoid complexity and you first want to know WHY before you invest dozens of hours learning a new skill. Is this you? Then keep reading. (Otherwise, leave now—and don’t tell me I didn’t warn you.)</p>
<p>So what are some applications of regular expressions?</p>
<p>As you read through the article, you can watch my explainer video:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="What are Regular Expressions Used For? 10 Applications" width="1100" height="619" src="https://www.youtube.com/embed/v6oi3Mll7sw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>Here’s the ToC that also gives you a quick overview of the regex applications:</p>
<h2>Search and Replace in a Text Editor</h2>
<p>The most straightforward application is to search a given text in your text editor. Say, your boss asks you to replace all occurrences of a customer <code>'Max Power'</code> with the name <code>'Max Power, Ph.D.,'</code>. </p>
<p>Here’s how it would look like:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-1-1024x731.png" alt="" class="wp-image-6507" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-1-1024x731.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/image-1-300x214.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-1-768x548.png 768w, https://blog.finxter.com/wp-content/uploads/2020/03/image-1.png 1028w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>I used the popular text editor Notepad++ (recommended for coders). At the bottom of the “Replace” window, you can see the box selection “Regular expression”. But in the example, we used the most straightforward regular expression: a simple string.</p>
<p>So you search and replace all occurrences of the string ‘Max Power’ and give it back to your boss. But your boss glances over your document and tells you that you’ve missed all occurrences with only <code>'Max'</code> (without the surname <code>'Power'</code>). What do you do?</p>
<p>Simple, you’re using a more powerful regex: <code>'Max( Power)?'</code> rather than only <code>'Max Power'</code>:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-2-1024x707.png" alt="" class="wp-image-6508" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-2-1024x707.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/image-2-300x207.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-2-768x531.png 768w, https://blog.finxter.com/wp-content/uploads/2020/03/image-2.png 1074w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Don’t worry, it’s not about the specific regex <code>'Max( Power)?'</code> and why it works. I just wanted to show you that it’s possible to match all strings that either look like this: <code>'Max Power'</code> or like this: <code>'Max'</code>. </p>
<p>Anyways, if you’re interested, you can read about the two regex concepts on the Finxter blog: <a rel="noreferrer noopener" aria-label="matching groups (opens in a new tab)" href="https://blog.finxter.com/python-re-groups/" target="_blank">matching groups</a> and the <a rel="noreferrer noopener" aria-label="question mark operator (opens in a new tab)" href="https://blog.finxter.com/python-re-question-mark/" target="_blank">question mark operator</a>. </p>
<h2>Searching Your Operating System for Files</h2>
<p>This is another common application: use regular expressions to search (and find) certain files on your operating system. </p>
<p>For example, <a href="https://superuser.com/questions/570760/find-filenames-with-certain-pattern-on-windows-command-line" target="_blank" rel="noreferrer noopener" aria-label="this (opens in a new tab)">this</a> guy tried to find all files with the following filename patterns:</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="">abc.txt.r12222
tjy.java.r9994</pre>
<p>He managed to do it on Windows using the command:</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="">dir * /s/b | findstr \.r[0-9]+$</pre>
<p>Large parts of the commands are a regular expression. In the final part, you can already see that he requires the file to end with <code>.r</code> and an arbitrary number of numeric symbols.</p>
<p>As soon as you’ve mastered regular expressions, this will cost you no time at all and your productivity with your computer will skyrocket. </p>
<h2>Searching Your Files for Text</h2>
<p>But what if you don’t want to find files with a certain filename but with a certain file content? Isn’t this much harder?</p>
<p>As it turns out, it isn’t! Well, if you use regular expression and grep.</p>
<p>Here’s what a grep guru would do to find all lines in a file <code>'haiku.txt'</code> that contain the word <code>'not'</code>. </p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-3.png" alt="" class="wp-image-6509" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-3.png 308w, https://blog.finxter.com/wp-content/uploads/2020/03/image-3-300x253.png 300w" sizes="(max-width: 308px) 100vw, 308px" /></figure>
<p><a rel="noreferrer noopener" aria-label="Grep (opens in a new tab)" href="https://en.wikipedia.org/wiki/Grep" target="_blank">Grep </a>is an aged-old file search tool written by famous computer scientist <a rel="noreferrer noopener" aria-label="Ken Thompson (opens in a new tab)" href="https://en.wikipedia.org/wiki/Ken_Thompson" target="_blank">Ken Thompson</a>. And it’s even more powerful than that: you can also search a bunch of files for certain content. </p>
<p>A Windows version of grep is the <a href="https://en.wikipedia.org/wiki/Find_(Windows)">find</a> utility.</p>
<h2>Search Engines</h2>
<p>Well, using regular expressions to find content on the web is considered the <a href="https://stackoverflow.com/questions/11119065/is-there-a-search-engine-that-support-regular-expression-search">holy grail</a> of search. But the web is a huge beast and supporting a full-fledged regex engine would be too demanding for Google’s servers. It costs a lot of computational resources. Therefore, nobody actually provides a search engine that allows all regex commands. </p>
<p>However, web search engines such as Google support a limited number of regex commands. For example, you can search queries that do NOT contain a specific word:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-4-1024x732.png" alt="" class="wp-image-6512" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-4.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/image-4-300x214.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-4-768x549.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>The search “Jeff -Bezos” will give you all the Jeff’s that do not end with Bezos. If a firstname is dominated like this, using advanced search operators is quite a useful extension.</p>
<p><a rel="noreferrer noopener" aria-label="Here's an in-depth Google guide (opens in a new tab)" href="http://www.googleguide.com/minus_operator.html" target="_blank">Here’s an in-depth Google search guide</a> that shows you how to use advanced commands to search the huge web even faster. </p>
<p>With the explosion of data and knowledge, mastering search is a critical skill in the 21st century.</p>
<h2>Validate User Input in Web Applications</h2>
<p>If you’re running a web application, you need to deal with user input. Often, users can put anything in the input fields (even <a rel="noreferrer noopener" aria-label="cross-site scripts (opens in a new tab)" href="https://en.wikipedia.org/wiki/Cross-site_scripting" target="_blank">cross-site scripts</a> to hack your webserver). Your application must validate that the user input is okay—otherwise you’re guaranteed to crash your backend application or database. </p>
<p>How can you validate user input? Regex to the rescue!</p>
<p>Here’s how you’d check whether </p>
<ul>
<li>The user input consists only of lowercase letters: <code>[a-z]+</code>,</li>
<li>The username consists of only lowercase letters, underscores, or numbers: <code>[a-z_0-9]+</code>, or</li>
<li>The input does not contain any parentheses: <code>[^\(\)]+</code>.</li>
</ul>
<p>With regular expressions, you can validate any user input—no matter how complicated it may seem. </p>
<p>Think about this: any web application that processes user input needs regular expressions. Google, Facebook, Baidu, WeChat—all of those companies work with regular expressions to validate their user input. This skill is wildly important for your success as a developer working for those companies (or any other web-based company for that matter).</p>
<p>Guess what Google’s ex tech lead argues is the top skill of a programmer? You got it: regular expressions!</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="5 must have skills to become a programmer (that you didn't know)" width="1100" height="619" src="https://www.youtube.com/embed/3MtrUf81k6c?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Extract Useful Information With Web Crawlers</h2>
<p>Okay, you can validate user input with regular expressions. But is there more? You bet there is.</p>
<p>Regular expressions are not only great to validate textual data but to extract information from textual data. </p>
<p>For example, say you want to gain some advantage over your competition. You decide to write a web crawler that works 24/7 exploring a subset of webpages. A webpage links to other webpages. By going from webpage to webpage, your crawler can explore huge parts of the web—fully automatized. </p>
<p>Imagine the potential! Data is the asset class of the 21st century and you can collect this valuable asset with your own web crawler. </p>
<p>A web crawler can be a Python program that downloads the HTML content of a website:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-5-1024x588.png" alt="" class="wp-image-6518" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-5-1024x588.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/image-5-300x172.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-5-768x441.png 768w, https://blog.finxter.com/wp-content/uploads/2020/03/image-5-1536x882.png 1536w, https://blog.finxter.com/wp-content/uploads/2020/03/image-5.png 1746w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>Your crawler can now use regular expressions to extract all outgoing links to other websites (starting with <code>"&lt;a href="</code>). </p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-6-1024x676.png" alt="" class="wp-image-6519" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-6-1024x676.png 1024w, https://blog.finxter.com/wp-content/uploads/2020/03/image-6-300x198.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-6-768x507.png 768w, https://blog.finxter.com/wp-content/uploads/2020/03/image-6.png 1155w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>A simple regular expression can now automatically get the stuff that follows—which is the outgoing URL. You can store this URL in a list and visit it at a later point in time.</p>
<p>As you’re extracting links, you can build a web graph, extract other information (e.g., embedded opinions of people) and run complicated subroutines on parts of the textual data (e.g., sentiment analysis). </p>
<p>Don’t underestimate the power of web crawlers when used in combination with regular expressions!</p>
<h2>Data Scraping and Web Scraping</h2>
<p>In the previous example, you’ve already seen how to extract useful information from websites with a web crawler.</p>
<p>But often the first step is to simply download a certain type of data from a large number of websites with the goal of storing it in a database (or a spreadsheet). But the data needs to have a certain structure.</p>
<p>The process of extracting a certain type of data from a set of websites and converting it to the desired data format is called <a rel="noreferrer noopener" aria-label="web scraping (opens in a new tab)" href="https://www.webharvy.com/articles/what-is-web-scraping.html" target="_blank">web scraping</a>. </p>
<p>Web scrapers are needed in finance startups, analytics companies, law enforcement, eCommerce companies, and social networks. </p>
<p>Regular expressions help greatly in processing the messy textual data. There are many different applications such as finding titles of a bunch of blog articles (e.g., for SEO).</p>
<p>A minimal example of using <a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener" aria-label="Python's regex library (opens in a new tab)">Python’s regex library</a> <code>re</code> for web scraping 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="">from urllib.request import urlopen
import re html = urlopen("https://blog.finxter.com/start-learning-python/").read() print(str(html))
titles = re.findall("\&lt;title\>(.*)\&lt;/title\>", str(html)) print(titles)
# ['What's The Best Way to Start Learning Python? A Tutorial in 10 Easy Steps! | Finxter']</pre>
<p>You extract all data that’s enclosed in opening and closing title tags: <code>&lt;title>...&lt;/title></code>. </p>
<h2>Data Wrangling</h2>
<p><a rel="noreferrer noopener" aria-label="Data wrangling (opens in a new tab)" href="https://en.wikipedia.org/wiki/Data_wrangling" target="_blank">Data wrangling</a> is the process of transforming raw data into a more useful format to simplify the processing of downstream applications. Every data scientists and machine learning engineer knows that data cleaning is at the core of creating effective machine learning models and extracting insights. </p>
<p>As you may have guessed already, data wrangling is highly dependent on tools such as regular expression engines. Each time you want to transform textual data from one format to another, look no further than regular expressions. </p>
<p>In Python, the regex method <code>re.sub(pattern, repl, string)</code> transforms a <code>string</code> into a new one where each occurrence of <code>pattern</code> is replaced by the new string <code>repl</code>. You can learn everything about the <a rel="noreferrer noopener" aria-label="substitution method on my other blog artic (opens in a new tab)" href="https://blog.finxter.com/python-regex-sub/" target="_blank">substitution method on my detailed blog tutorial (+video)</a>. </p>
<p>This way, you can transform currencies, dates, or stock prices into a common format with regular expressions.</p>
<h2>Parsing</h2>
<p>Show me any parser and I show you a tool that leverages hundreds of regular expressions to process the input quickly and effectively.</p>
<p>You may ask: what’s a parser anyway? And you’re right to ask (there are no dumb questions). A <a href="https://en.wikipedia.org/wiki/Parsing">parser</a> translates a string of symbols into a higher-level abstraction such as a formalized language (often using an underlying grammar to “understand” the symbols). You’ll need a parser to write your own programming language, syntax system, or text editor. </p>
<p>For example, if you write a program in the Python programming language, it’s just a bunch of characters. Python’s parser brings order into the chaos and translates your meaningless characters into more meaningful abstractions (e.g. keywords, variable names, or function definitions). This is then used as an input for further processing stages such as the execution of your program.</p>
<p>If you’re looking at how parsers are implemented, you’ll see that they heavily rely on regular expressions. This makes sense because a regular expression can easily analyze and catch parts of your text. For example, to extract function names, you can use the following regex in your parser:</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 code = '''
def f1(): return 1 def f2() return 2 ''' print(re.findall('def ([a-zA-Z0-9_]+)', code))
# ['f1', 'f2']</pre>
<p>You can see that our mini parser extracts all function names in the code. Of course, it’s only a minimal example and it wouldn’t work for all instances. For example, you can use more characters than the given ones to define a function name. </p>
<p>If you’re interested in writing parsers or learning about compilers, regular expressions are among the most useful tools in existence!</p>
<h2>Programming Languages</h2>
<p>Yes, you’ve already learned about parsers in the previous point. And parsers are needed for any programming language. To put it bluntly: there’s no programming language in the world that doesn’t rely on regular expressions for their own implementation.</p>
<p>But there’s more: regular expressions are also very popular when writing code in any programming language. Some programming languages such as Perl provide built-in regex functionality: you don’t even need to import an external library.</p>
<p>I assure you, if you’re becoming a professional coder, you will use regular expressions in countless of coding projects. And the more you use it, the more you’ll learn to love and appreciate the power of regular expressions.</p>
<h2>Syntax Highlighting Systems</h2>
<p>Here’s how my standard coding environment looks like:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-7.png" alt="" class="wp-image-6522" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-7.png 786w, https://blog.finxter.com/wp-content/uploads/2020/03/image-7-300x276.png 300w, https://blog.finxter.com/wp-content/uploads/2020/03/image-7-768x707.png 768w" sizes="(max-width: 786px) 100vw, 786px" /></figure>
<p>Any code editor provides syntax highlighting capablities:</p>
<ul>
<li>Function names may be blue.</li>
<li>Strings may be yellow.</li>
<li>Comments may be red.</li>
<li>And normal code may be white.</li>
</ul>
<p>This way, reading and writing code becomes far more convenient. More advanced IDEs such as PyCharm provide dynamic tooltips as an additional feature.</p>
<p>All of those functionalities are implemented with regular expressions to find the keywords, function names, and normal code snippets—and, ultimately, to parse the code to be highlighted and enriched with additional information.</p>
<h2>Lexical Analysis in a Compiler</h2>
<p>In compiler design, you’ll need a lexical analyzer:</p>
<blockquote class="wp-block-quote">
<p>The lexical analyzer needs to scan and identify only a finite set of valid string/token/lexeme that belong to the language in hand. It searches for the pattern defined by the language rules.</p>
<p>Regular expressions have the capability to express finite languages by defining a pattern for finite strings of symbols. The grammar defined by regular expressions is known as <strong>regular grammar</strong>. The language defined by regular grammar is known as <strong>regular language</strong>.</p>
<p><cite><a href="https://www.tutorialspoint.com/compiler_design/compiler_design_regular_expressions.htm" target="_blank" rel="noreferrer noopener" aria-label="Source (opens in a new tab)">Source</a></cite></p></blockquote>
<p>As it turns out, regular expressions are the gold standard for creating a lexical analyzer for compilers. </p>
<p>I know this may sound like a very specific application but it’s an important one nonetheless.</p>
<h2>Formal Language Theory</h2>
<p>Theoretical computer science is the foundation of all computer science. The great names in computer science, <a href="https://en.wikipedia.org/wiki/Alan_Turing">Alan Turing</a>, <a rel="noreferrer noopener" aria-label="Alonzo Church (opens in a new tab)" href="https://en.wikipedia.org/wiki/Alonzo_Church" target="_blank">Alonzo Church</a>, and <a href="https://en.wikipedia.org/wiki/Stephen_Cole_Kleene">Steven Kleene</a>, all spent significant time and effort studying and developing regular expressions.</p>
<p>If you want to become a great computer scientist, you need to know your fair share of theoretical computer science. You need to know about <a href="https://en.wikipedia.org/wiki/Formal_language">formal language theory</a>. You need to know about regular expressions that are at the heart of these theoretical foundations.</p>
<p>How do regular expressions relate to formal language theory? Each regular expression defines a “language” of acceptable words. All words that match the regular expression are in this language. All words that do not match the regular expression are not in this language. This way, you can create a precise sets of rules to describe any formal language—just by using the power of regular expressions.</p>
<h2>Where to Go From Here?</h2>
<p>Regular expressions are widely used for many practical applications. The ones described here are only a small subsets of the ones used in practice. However, I hope to have given you a glance into how important and relevant regular expressions have been, are, and will remain in the future.</p>
<p>Want to learn more about how to convert your computer science skills into money? Check out my <a rel="noreferrer noopener" aria-label="free webinar that shows you a step-by-step approach to build your thriving online coding business (opens in a new tab)" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">free webinar that shows you a step-by-step approach to build your thriving online coding business</a> (working from home). You don’t need to have any computer science background though. The only thing you need is the ambition to learn.</p>
<p>Click: <a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener" aria-label="https://blog.finxter.com/webinar-freelancer/ (opens in a new tab)">https://blog.finxter.com/webinar-freelancer/</a></p>
</div>


https://www.sickgaming.net/blog/2020/03/03/what-are-regular-expressions-used-for-10-applications/