<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/regular-expressions-exercises-part-1/"></div></div><div><a data-url="https://www.r-bloggers.com/regular-expressions-exercises-part-1/" data-counturl="https://www.r-bloggers.com/regular-expressions-exercises-part-1/" data-count="horizontal" data-text="Regular Expressions Exercises – Part 1" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-exercises.com/2016/10/30/regular-expressions-part-1/"> R-exercises</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a target="_blank" rel="nofollow" href="https://i0.wp.com/r-exercises.com/wp-content/uploads/2016/10/pattern1.jpg?resize=261%2C193"><img alt="pattern1" class="wp-image-2430" src="https://i0.wp.com/r-exercises.com/wp-content/uploads/2016/10/pattern1.jpg?resize=261%2C193" data-recalc-dims="1"></a><br>
A common task performed during data preparation or data analysis is the manipulation of strings.</p>
<p>Regular expressions are meant to assist in such and similar tasks.</p>
<p>A <i>regular expression</i> is a <strong>pattern</strong> that describes a set of strings.</p>
<p>Regular expressions can range from simple patterns (such as finding a single number) thru complex ones (such as identifing UK postcodes).</p>
<p>R implements a set of “regular expression rules” that are basically shared by other programming languages as well, and even allow the implementation of some nuances, such as Perl-like regular expressions.</p>
<p>Also, sometimes specific patterns may or may not be found, according to the system locales.</p>
<p>The implementation of those <strong>patterns</strong> can be performed thru several base-r functions, such as:</p>
<ul>
<li><code>grep</code></li>
<li><code>grepl</code></li>
<li><code>regexpr</code></li>
<li><code>gregexpr</code></li>
<li><code>sub</code></li>
<li><code>gsub</code></li>
<li><code>strsplit</code></li>
</ul>
<p>Since this topic includes both learning a set of rules and several different r functions, I’ll split this subject in a 3-sets series.</p>
<p>Answers to the exercises are available <a target="_blank" rel="nofollow" href="http://r-exercises.com/2016/10/30/regular-expressions-part-1-solution">here</a>.</p>
<p>Although with <code>regex</code>, you can get correct results in more than one way, if you have different solutions, feel free to post them.</p>
<p><strong> </strong></p>
<h4>Character class</h4>
<p>A character class is a list of characters enclosed between square brackets (e.g. [ and ]), which matches any *single* character in that list.<br>
For example [0359abC] means “find a pattern with one of the digits/characters 0,3,5,9,”a”,”b” or “C”.<br>
There are some “shortcuts” that allow us finding specific ranges of digits or characters:</p>
<ul>
<li>[0-9] means any digit</li>
<li>[A-Z] means any upper case character</li>
<li>[a-z] means any lower case character</li>
</ul>
<p>Let’s create a variable called <code> text1 </code> and populate it with the value “The current year is 2016”</p>
<p><strong>Exercise 1</strong><br>
Create a variable called <code>my_pattern</code> and implement the required pattern for finding <strong>any</strong> digit in the variable text1.<br>
Use function <code> grepl </code> to verify if there is a digit in the string variable</p>
<p><strong>Exercise 2</strong><br>
Use function <code>gregexpr</code> to find <strong>all</strong> the positions in <code>text1</code> where there is a digit.<br>
Place the results in a variable called <code> string_position </code></p>
<p><strong> </strong></p>
<h4>Predefined classes of characters</h4>
<p>In many cases, we will look for specific types of characters (for example, any digit, any letter, any whitespace, etc).<br>
For this purpose, there are several predefined classes of characters that save us a lot of typing.</p>
<p>Note: The interpretation of some predefined classes depends on the locale. The “standard” interpretation is that of the POSIX locale.</p>
<p>Below are some “popular” predefined classes and their meaning:<br>
1. <code>[:alnum:]</code><br>
Alphanumeric characters: <code>[:alpha:]</code> and <code>[:digit:]</code>.</p>
<p>2. <code>[:alpha:]</code><br>
Alphabetic characters: <code>[:lower:]</code> and <code>[:upper:]</code> can also be used.</p>
<p>3. <code>[:digit:]</code><br>
Digits: 0 1 2 3 4 5 6 7 8 9.</p>
<p>4. <code>[:blank:]</code><br>
Blank characters: space and tab, and possibly other locale-dependent characters<br>
such as non-breaking space.</p>
<p><strong>Exercise 3</strong><br>
Create a variable called <code>my_pattern</code> and implement the required pattern for finding <strong>one</strong> digit and <strong>one</strong> uppercase alphanumeric character, in variable <code>text1</code>.<br>
This time, combine predefined classes in the regex pattern.<br>
Use function <code> grepl </code> to verify if the searched pattern exists on the string.</p>
<p><strong>Exercise 4</strong><br>
Use function <code>regexpr</code> to find the position of the first space in text1.<br>
Place the results in a variable called <code> first_space </code> and</p>
<p><strong> </strong></p>
<h4>Special single character</h4>
<p>The period (“.”) matches any single character.<br>
<strong>Exercise 5</strong><br>
Create a pattern that checks in <code>text1</code> if there is a lowercase character, followed by any character and then by a digit.</p>
<p><strong>Exercise 6</strong><br>
Find the starting position of the above string. Place the results in a variable called <code>string_pos2</code></p>
<p><strong> </strong></p>
<h4>Special symbols</h4>
<p>There are several “special symbols” that assist in the definition of specific patterns.<br>
Pay attention that in R, you should append an extra backslash when using those special symbols:<br>
The symbol <code>\w</code> matches a ‘word’ character and <code>\W</code> is its negation.<br>
Symbols <code>\d</code>, <code>\s</code>, <code>\D</code> and <code>\S</code> denote the digit and space classes and their negations.<br>
As you may have noticed, some special symbols have their parallel “predefined classes”.<br>
(For example, <code>\d</code> equals <code>[0-9]</code> and equals <code>[:digit:]</code>)</p>
<p><strong>Exercise 7</strong><br>
Find the following pattern: one space followed by two lowercase letters and one more space.<br>
Use a function that returns the starting point of the found string and place its result in <code>string_pos3</code>.</p>
<p><strong> </strong></p>
<h4>Metacharacters</h4>
<p>There are several metacharacters in the “regex syntax”. Here I’ll introduce two popular ones:<br>
The caret <code>(&quot;^&quot;)</code> – means: find a pattern starting from the <strong>beginning</strong> of the string<br>
The dollar sign <code>(&quot;$&quot;)</code> – means: find a pattern starting from the <strong>end</strong> of the string.</p>
<p><strong>Exercise 8</strong><br>
Using the <code>sub</code> function, replace the pattern found on the previous exercice by the string ” is not ”<br>
Place the resulting string in <code>text2</code> variable.</p>
<p><strong> </strong></p>
<h4>Repetition Characters</h4>
<p>There are several ways of dealing with the repetition of characters in the “regex syntax”. Here I’ll introduce the “Curly brackets” syntax:<br>
<code>{n}</code> The preceding item is matched exactly n times.</p>
<p><code>{n,}</code> The preceding item is matched n or more times.</p>
<p><code>{n,m}</code> The preceding item is matched at least n times, but not more than m times.</p>
<p>By default repetition is greedy, so the maximal possible number of repeats is used.</p>
<p><strong>Exercise 9 </strong><br>
Find in <code>text2</code> the following pattern: Four digits starting at the end of the string.<br>
Use a function that returns the starting point of the found string and place its result in <code>string_pos4</code>.</p>
<p><strong>Exercise 10</strong><br>
Using the <code>substr</code> function, and according to the position of the string found in the previous excercise, extract the first two digits found at the end of <code>text2</code>.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/regular-expressions-exercises-part-1/"></div></div><div><a data-url="https://www.r-bloggers.com/regular-expressions-exercises-part-1/" data-counturl="https://www.r-bloggers.com/regular-expressions-exercises-part-1/" data-count="vertical" data-text="Regular Expressions Exercises – Part 1" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-exercises.com/2016/10/30/regular-expressions-part-1/"> R-exercises</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Xmp2NUKmDFk"></a></div>