{"id":7,"date":"2022-08-09T17:36:00","date_gmt":"2022-08-09T16:36:00","guid":{"rendered":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/?p=7"},"modified":"2022-08-09T17:36:00","modified_gmt":"2022-08-09T16:36:00","slug":"demystify-regular-expressions","status":"publish","type":"post","link":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/2022\/08\/09\/demystify-regular-expressions\/","title":{"rendered":"Demystify regular expressions"},"content":{"rendered":"<p>Have you ever filled a form where you got an &#8220;invalid email address&#8221; error? These alerts are commonly built using <strong>regular expressions<\/strong>. They evaluate the field value against a set of rules and report if the value complies with them. Regular expressions allow much more than this simple example.<\/p>\n<p>I was introduced to regular expressions (<strong>RegEx <\/strong>for short) in 2009 when studying Finite Automaton. A Finite Automaton (aka Finite State Machine (FSM)) is a state machine that accepts or rejects input based on a set of rules. The example I found most interesting is the concept of an arcade Galaga machine that would, in the 80s, accept a coin as the input. It would return you a credit to spend on the game if the coin was 10p. If the coin was another coin, it would reject the input and return the coin back to you.<\/p>\n<p>One of the most know automaton machines was <a href=\"https:\/\/en.wikipedia.org\/wiki\/Alan_Turing\">Alan Turing<\/a>&#8216;s <a href=\"https:\/\/en.wikipedia.org\/wiki\/Turing_machine\">Turing machine<\/a> which was used to break the Enigma machine in the 1940s. Regular expressions came shortly after in 1951 by mathematician <a href=\"https:\/\/en.wikipedia.org\/wiki\/Stephen_Cole_Kleene\">Stephen Kleene<\/a>, and its first know application was made in 1961 by <a href=\"https:\/\/en.wikipedia.org\/wiki\/Ken_Thompson\">Ken Thomson<\/a> on his Unix text editor &#8220;ed&#8221;.<\/p>\n<h2>How does RegEx work?<\/h2>\n<p>RegEx uses a search pattern that can match, replace and manage text. It can significantly simplify going through many text files, logs, spreadsheets, etc. I love using it in my code when I need to match, select and manipulate objects. Very useful in XPath, python and PowerShell scripts.<\/p>\n<h2>RegEx syntax summary<\/h2>\n<pre>\r\n<strong>Literal characters:<\/strong> Except for special characters all characters match their literal characters. E.g. the regex for \"A\" matches the string \"A\", \"9\" matches the number 9, \"=\" matches \"=\", etc.<br>\r\n<strong>Special Characters:<\/strong> ., +, *, ?, ^, $, (, ), [, ], {, }, |, \\.<br>\r\n<strong>Escape sequence:<\/strong> If you need to match any of the special characters, you need to add an escape character \"\\\". E.g. \"\\\\\" will match \"\\\" and \"\\[\" will match \"[\"<br>\r\n<strong>OR operator \"|\":<\/strong> you can try to match multiple strings like \"Robert|Rob\" this will match any of the words \"Robert\" or \"Rob\"<br>\r\n<strong>Metacharacters:<\/strong><br>\r\n    <span style=\"padding-left:20px\">. will match any single character <\/span><br>\r\n    <span style=\"padding-left:20px\">\\d will match any single digit<\/span><br>\r\n    <span style=\"padding-left:20px\">\\D will match any NON single digit<\/span><br>\r\n    <span style=\"padding-left:20px\">\\w will match any single lower\/upper case A to Z and 0 to 9<\/span><br>\r\n    <span style=\"padding-left:20px\">\\W will match any single NON lower\/upper case A to Z and 0 to 9<\/span><br>\r\n    <span style=\"padding-left:20px\">\\s will match any single space<\/span><br>\r\n    <span style=\"padding-left:20px\">\\S will match any single NON space<\/span><br>\r\n<strong>Position Anchors:<\/strong><br>\r\n    <span style=\"padding-left:20px\">^ start of line<\/span><br>\r\n    <span style=\"padding-left:20px\">$ end of line<\/span><br>\r\n    <span style=\"padding-left:20px\">\\r carriage return<\/span><br>\r\n    <span style=\"padding-left:20px\">\\n line feed<\/span><br>\r\n<strong>Laziness matching:<\/strong><br>\r\n    <span style=\"padding-left:20px\">. any single character<\/span><br>\r\n    <span style=\"padding-left:20px\">* multiple times<\/span><br>\r\n    <span style=\"padding-left:20px\">+ one or more times<\/span><br>\r\n    <span style=\"padding-left:20px\">? zero or more times<\/span><br>\r\n    <span style=\"padding-left:20px\">{,m} between 0 and m times<\/span><br>\r\n    <span style=\"padding-left:20px\">{n,} more than n times<\/span><br>\r\n    <span style=\"padding-left:20px\">{n,m} between n and m times<\/span><br>\r\n<strong>Capturing groups:<\/strong><br>\r\n    <span style=\"padding-left:20px\">() will capture a back reference to the regex within the parentheses. You can access these by referencing them as E.G. \\1, $1, {1}, etc, depending on the language\/tool used.<\/span><br>\r\n<\/pre>\n<p><strong>Powershell:<\/strong><\/p>\n<div class=\"highlight\">\n<pre style=\"width: 100%;font-size: 12px;line-height: 1.5em;background: #FAFAFA;background-image: linear-gradient(#F9F9F9 50%, #FDFDFD 50%);background-size: 3em 3em;background-position: 0px 10px;border-left: 7px solid #444\">\r\n<code style=\"width: 100%\">  <span style=\"color: #009900\"># How to show any occurrence of the word error in one folder<\/span>            <br>  <span style=\"color: #990000;font-weight: bold\">Get-ChildItem<\/span> <span style=\"color: #000080\">-Path<\/span> <span style=\"color: #008080\">$logFolder<\/span> <span style=\"font-weight: bold\">|<\/span> <span style=\"color: #990000;font-weight: bold\">Select-String<\/span> <span style=\"color: #000080\">-Pattern<\/span> <span style=\"color: #d14\">'Error'<\/span><\/code><\/pre>\n<\/div>\n<p><strong>Python:<\/strong><\/p>\n<div class=\"highlight\">\n<pre style=\"width: 100%;font-size: 12px;line-height: 1.5em;background: #FAFAFA;background-image: linear-gradient(#F9F9F9 50%, #FDFDFD 50%);background-size: 3em 3em;background-position: 0px 10px;border-left: 7px solid #444\">\r\n<code style=\"width: 100%\">  <span style=\"color: #009900\"># How to click on an a HTML object using Python and Selenium<\/span>            <br>  <span style=\"color: #000080\">driver.find_element(By.XPATH,<\/span><span style=\"color: #dd0000\">\"\/\/a[i[contains(@value,'objName')]]\"<\/span> <span style=\"color: #000080\">).click()<\/span><\/code><\/pre>\n<\/div>\n<p>You can try regular expressions straight from your browser. I found it useful when automating web checks or completing web scraping activities. If you use Chrome, press ctrl_shift+i (F12 in most browsers) to open the developer tools. In the &#8220;console&#8221; tab, you should be able to identify if an element exists by typing <code>\"$x('expression')\"<\/code> and Chrome will let you know if the element exists.<br \/>\n<img loading=\"lazy\" decoding=\"async\" width=\"471\" height=\"123\" src=\"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/files\/2022\/08\/chrome.png\" alt=\"\" class=\"alignnone size-full wp-image-35\" \/><\/p>\n<p>This can also be tested within the &#8220;elements tab&#8221;:<br \/>\n<img loading=\"lazy\" decoding=\"async\" width=\"467\" height=\"556\" src=\"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/files\/2022\/08\/chrome2.png\" alt=\"Elements XPath\" class=\"alignnone size-full wp-image-40\" \/><\/p>\n<p>I also tend to use it with text editors (Notepad++, Geany, etc.) for quick text cleanups.  As I was writing this, I wanted to add the entire list of rooms available on a form list box existing in one of the ICT events systems. I could have typed them one by one, but that is not a good way to do it if you have more than a handful of entries. I&#8217;ve copied the HTML element I wanted and used Notepad++. <\/p>\n<p>I wanted the room names just like the ones highlighted below:<br \/>\n<img loading=\"lazy\" decoding=\"async\" width=\"1187\" height=\"839\" src=\"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/files\/2022\/08\/notepad1.png\" alt=\"\" class=\"alignnone size-full wp-image-36\" \/><\/p>\n<p>Using the &#8220;Replace&#8221; option under the &#8220;Search&#8221; menu on NotePad++ and having the &#8220;Regular Expression&#8221; option ticked, I typed <code>^.*([0-9a-zA-Z. ]*)[\\t ]*+<\/code> and replaced it with <code>\\1<\/code>:<br \/>\n<img loading=\"lazy\" decoding=\"async\" width=\"1242\" height=\"871\" src=\"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/files\/2022\/08\/notepad2.png\" alt=\"\" class=\"alignnone size-full wp-image-37\" \/><br \/>\n<code><span style=\"color: #ff0000\">^<\/span><span style=\"color: #00aa00\">.*<\/span><span style=\"color: #ff00ff\">&lt;option<\/span><span style=\"color: #aaaa00\">.*<\/span><span style=\"color: #5500ff\">&gt;<\/span><span style=\"color: #910099\">([0-9a-zA-Z. ]*)<\/span><span style=\"color: #00a2aa\">[\\t ]*<\/span><span style=\"color: #f0c115\">&lt;\/.*&gt;<\/span><\/code> is signalling to the search and replace function that I wanted to find:<\/p>\n<ol style=\"padding-left:20px\">\n<li><span style=\"color: #ff0000\">start my search from the beginning of the line<\/span><\/li>\n<li><span style=\"color: #00aa00\">has any number of caracters<\/span> before it encounters <span style=\"color: #ff00ff\">&lt;option<\/span><\/li>\n<li><span style=\"color: #aaaa00\">has any number of caracters<\/span> before it encounters <span style=\"color: #5500ff\">&gt;<\/span><\/li>\n<li>This part is a group because it is wrapped with (). <span style=\"color: #910099\">Looks for any word of any length composed of numbers, lower\/upper case characters from A to Z, dots and spaces.<\/span><\/li>\n<li><span style=\"color: #00a2aa\">has any number of spaces<\/span><\/li>\n<li><span style=\"color: #f0c115\">has any number of characters between &lt;&gt; <\/li>\n<\/ol>\n<p>The replace box signals that the entire word match should be replaced with the first group encountered in the match. The result can be seen as:<br \/>\n<img loading=\"lazy\" decoding=\"async\" width=\"321\" height=\"758\" src=\"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/files\/2022\/08\/notepad3.png\" alt=\"Console XPath\" class=\"alignnone size-full wp-image-38\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>There are hundreds of sites explaining RegEx but I&#8217;ll point you to the reputable Microsoft page: <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/standard\/base-types\/regular-expression-language-quick-reference\" rel=\"noopener\" target=\"_blank\">https:\/\/docs.microsoft.com\/en-us\/dotnet\/standard\/base-types\/regular-expression-language-quick-reference<\/a> for reference.<\/p>\n<p>The potential for using RegEx is immense. Have you used it before? Any good examples you can share?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Have you ever filled a form where you got an &#8220;invalid email address&#8221; error? These alerts are commonly built using regular expressions. They evaluate the field value against a set of rules and report if the value complies with them. Regular expressions allow much more than this simple example. I was introduced to regular expressions [&hellip;]<\/p>\n","protected":false},"author":1672,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320486],"tags":[],"class_list":["post-7","post","type-post","status-publish","format-standard","hentry","category-tools-and-tips"],"_links":{"self":[{"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/posts\/7","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/users\/1672"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/comments?post=7"}],"version-history":[{"count":77,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/posts\/7\/revisions"}],"predecessor-version":[{"id":93,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/posts\/7\/revisions\/93"}],"wp:attachment":[{"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/media?parent=7"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/categories?post=7"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs-staging.imperial.ac.uk\/technology-office\/wp-json\/wp\/v2\/tags?post=7"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}