Introduction to Regular Expressions


Published on

^Regular Expressions is one of those tools that every developer should have in their toolbox. You can do your job without regular expressions, but knowing when and how to use them will make you a much more efficient and marketable developer. You'll learn how regular expressions can be used for validating user input, parsing text, and refactoring code. We'll also cover various tools that can be used to help you write and share expressions.$

Published in: Technology, News & Politics
1 Comment
  • Very interesting. Thanks.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • I just wanted to get this famous quote out of the way from the beginning. Like all great quotes, it has been falsely attributed all over the place. See for a comprehensive investigation on where the quote originates.
  • If you’re never seen a regular expression before, it might look like Q*bert’s language to you.
  • These are all examples of regular expressions. They were all created with the intent of matching email addresses. As you can see, they’re very different from one another.
  • Regular expressions are often called a “write only language” and aren’t easily understood. To a novice they don’t even look like they have any meaning.
  • Kleene is pronounced “clay-knee”
  • Kenneth Lane Thompson, or just ‘ken’ in hacker circles, is often credited for creating the Unix operating system along with Dennis Ritchie
  • Unix command line tool which borrowed Regular Expression pattern matching from the “ed” editor.
  • Theregex library was eventually used to develop the PCRE library – Perl Compatible Reguarl Expressions. Most major programming languages these days use regular expressions based on the PCRE, including Java, .NET and Ruby.
  • Without knowing regular expressions you could certainly accomplish this task, but it would take much longer, be more complex, and much more likely to contain bugs.
  • Here’s some c# code that I threw together in a few minutes to parse a text file. There are bugs in the code and requirements that it doesn’t meet. Also, if requirements were to be added, this code would be more difficult to refactor than a regex.
  • This solution is in Perl. I could have re-written it in c# for good comparison with my previous slide, but I decided that the original example solution looks much nicer. By the way, this example is taken from Mastering Regular Expressions by Jeffrey Friedl
  • Knowing regular expressions won’t make you a hero, but you may feel like one when you’ve saved lots of time.
  • The basics of regular expressions start with literal characters. Any character, except for a small list of reserved characters which will be covered next, is considered a literal character. This example has a regex “is” which is two literal characters.
  • The regex “a” matches any letter “a” in the target string, even if its inside a word.
  • Some regex engines have the option to turn off case sensitivity. Some engines may have this option on by default.
  • These are all reserved characters, also known as meta-characters.
  • Special characters can be escaped with a backslash, as demonstrated in the example.
  • The curly brace characters are reserved, but only when in the context of a repetition modifier, and don’t need to be escaped otherwise. You can escape them without any side effects.
  • There are other non-printable characters too, especially when you use unicode. You can also reference ASCII character codes, but I don’t see the need to show an example of this.
  • The period, or dot, character matches any single character. There is an exception to this – if the engine is in single line mode (which used to be the only mode, but now is usually off by default) then the period will not match a new line. Javascript and VBScript don’t have a multi-line option, but [sS] works.The period is the most common meta-character, but that is because it is often mis-used.
  • Also known as Character Sets match only one of the characters inside the square brackets.
  • The hyphen, or dash, character inside a character class indicates a range of characters. The example would match any hexadecimal value. Note that the hyphen can be escaped inside a character class, but doesn’t need to be escaped if its at the beginning or end because its not a range in that context.
  • A caret just inside a character negates the match. Note that the example won’t match the string “Iraq” because there is no character following the q. Also, “Qatar” isn’t matched because the Q is capitalized.
  • The caret and hyphen characters are only reserved when they’re used in a context that could suggest a negation (for carets) or a range (for hyphens).
  • These can be used inside and outside of character classes. All of these aren’t necessary, but are shortcuts that make it easier to write readable regular expressions – HA!Note that in the example the match includes the space before the numbers, but I couldn’t easily represent that with coloring.
  • These are the negated versions of the shorthand character classes from the previous slide.
  • Like the period, the asterisk is overused and dangerous.
  • Like the period, the asterisk is overused and dangerous.
  • The question mark can also modify a repetition symbol to make it non-greedy or lazy, but that’s a more advanced subject. Its all about context.
  • Anchors don’t match a character, they match a position which could be before, after or between characters. In this example, the string only matches because there is no whitespace before the word “vacation”
  • Note that anchors can result in a zero length match. For example, a regex of just “$” matches the position at the end of a line, but the match has no characters. This can be useful or cause issues in your code!
  • Note that another exception is a new line at the end of a file will not be matched by $ or . The z shorthand character class will handle this circumstance.
  • Note that the words “at”, “that” and “ate” don’t contain a match in the example.
  • Regular expressions are eager, which means they match as soon as they can. This means that the order of similar character classes in an alternation can affect the result. In the example, the “and” match is found first, even though the full word “android” exists. If the character classes were switched, the whole “and” word would still match, but the whole “android” word would match instead of just the beginning of the word.
  • Greediness causes the example to always match the full “android” instead of just “and” which is also a valid match.
  • The ? mark after a repetition operator (*+?) makes it lazy.
  • Using parenthesis, or round braces, to group a character set not only groups those characters together to apply repetition to them, but it also creates a back reference. A back reference stores the grouped part of the match for use later in the regex. Back references can also be used for replaces.In the example, “agici” doesn’t match because the group is “a” not “i”.
  • The groups can be named with single parenthesis instead of greater/less than characters.
  • This example matches a “q” not followed by a “u”. Unlike the example earlier in the presentation, this regex won’t match the character following the “q”.
  • This example matches a “q” followed by a “u”, but notice that the “u” is not included with that match.
  • This example matches a “q” followed by a “u”, but notice that the “u” is not included with that match.
  • Introduction to Regular Expressions

    1. 1. Introduction toRegular Expressions<br />Matt Casto<br /><br />
    2. 2. Introduction toRegular Expressions<br />Matt Casto<br />Quick Solutions<br /><br />
    3. 3. “Some people, when confronted with a problem, think “I know, I&apos;ll use regular expressions. Now they have two problems.”<br />- Jamie Zawinski, August 12, 1997<br />
    4. 4.
    5. 5. What are Regular Expressions?<br />^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$<br />[w-]+@([w-]+.)+[w-]+<br />^.+@[^.].*.[a-z]{2,}$<br />^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$<br />
    6. 6.
    7. 7. History<br />Stephen Cole Kleene<br />American mathematician credited for inventing Regular Expressions in the 1950’s using a mathematic notation called regular sets.<br />
    8. 8. History<br />Ken Thompson<br />American pioneer of computer science who, among many other things, used Kleene’s regular sets for searching in his QED and ed text editors.<br />
    9. 9. History<br />grep<br />Global Regular Expression Print<br />
    10. 10. History<br />Henry Spencer<br />Wrote the regex library which is what Perl and Tcl languages used for regular expressions.<br />
    11. 11. Why Should You Care?<br />Example: finding duplicate words in a file.<br />Requirements:<br /><ul><li> Output lines that contain duplicate words
    12. 12. Find doubled words that expand lines
    13. 13. Ignore capitalization differences
    14. 14. Ignore HTML tags</li></li></ul><li>
    15. 15. Why Should You Care?<br />Example: finding duplicate words in a file.<br />Solution:<br />$/ = “. ”;<br />while (&lt;&gt;) {<br /> next if !s/([a-z]+)((?:s&lt;[^&gt;]+&gt;)+)(1)/e[7m$1e[m$2e[7m$3e[m/ig;<br /> s/^(?:[^e]* )+//mg;<br /> s/^/$ARGV: /mg;<br /> print;<br />}<br />
    16. 16.
    17. 17. Literal Characters<br />Any character except a small list of reserved characters.<br />regex<br />is<br />Jack is a boy<br />match in target string<br />
    18. 18. Literal Characters<br />Literals will match characters in the middle of words.<br />regex<br />a<br />Jack is a boy<br />matches in target string<br />
    19. 19. Literal Characters<br />Literals are case sensitive – capitalization matters!<br />regex<br />j<br />Jack is a boy<br />NOT a match<br />
    20. 20. Special Characters<br />[ ^ $ . | ? * + ( )<br />
    21. 21. Special Characters<br />You can match special characters by escaping them with a backslash.<br />1+1=2<br />I wrote 1+1=2 on the chalkboard.<br />
    22. 22. Special Characters<br />Some characters, such as { and } are only reserved depending on context.<br />if (true) {<br />else if (true) { beep; }<br />
    23. 23. Non-Printable Characters<br />Some literal characters can be escaped to represent non-printable characters.<br /> – tab<br /> – carriage return<br /> – line feed<br />a – bell<br />e – escape<br />f – form feed<br />v – vertical tab<br />
    24. 24. Period<br />The period character matches any single character.<br />a.boy<br />Jack is a boy<br />
    25. 25. Character Classes<br />Used to match only one of the characters inside square braces.<br />[Gg]r[ae]y<br />Grayson drives a grey sedan.<br />
    26. 26. Character Classes<br />Hyphen is a reserved character inside a character class and indicates a range.<br />[0-9a-fA-F]<br />The HTML codefor White is #FFFFFF<br />
    27. 27. Character Classes<br />Caret inside a character class negates the match.<br />q[^u]<br />Qatar is home to quite a lot of Iraqi citizens, but is not a city in Iraq<br />
    28. 28. Character Classes<br />Normal special characters are valid inside of character classes. Only ] ^ and – are reserved.<br />[+*]<br />6 * 7 and 18 + 24 both equal 42<br />
    29. 29. Shorthand Character Classes<br />d – digit or [0-9]<br />w – word or [A-Za-z0-9_]<br />s – whitespace or [ ] (space, tab, CR, LF)<br />[sd]<br />1 + 2 = 3<br />
    30. 30. Shorthand Character Classes<br />D – non-digit or [^d]<br />W – non-word or [^w]<br />S – non-whitespace or [^s]<br />[D]<br />1 + 2 = 3<br />
    31. 31. Repetition<br />The asterisk repeats the preceding character class 0 or more times.<br />&lt;[A-Za-z][A-Za-z0-9]*&gt;<br />&lt;HTML&gt;Regex is &lt;b&gt;Awesome&lt;/b&gt;&lt;/HTML&gt;<br />
    32. 32. Repetition<br />The plus repeats the preceding character class 1 or more times.<br />&lt;[A-Za-z0-9]+&gt;<br />Watch out for invalid &lt;HTML&gt; tags like &lt;1&gt; and &lt;&gt;!<br />
    33. 33. Repetition<br />The question mark repeats the preceding character class 0 or 1 times, in effect making it optional.<br />&lt;/?[A-Za-z][A-Za-z0-9]*&gt;<br />&lt;HTML&gt;Regex is &lt;b&gt;Awesome&lt;/b&gt;&lt;/HTML&gt;<br />
    34. 34. Anchors<br />The caret anchor matches the position before the first character in a string.<br />^vac<br />vacation evacuation<br />
    35. 35. Anchors<br />The dollar sign anchor matches the position after the last character in a string.<br />tion$<br />vacation evacuation<br />
    36. 36. Anchors<br />The caret and dollar sign anchors match the start and end of the line if the engine has multi-line turned on.<br />tion$<br />vacation evacuation<br />has ruined my evaluation<br />
    37. 37. Anchors<br />The A and  shorthand character classes are like<br />^ and $ but only match the start and end of the string.<br />tion<br />vacation evacuation<br />has ruined my evaluation<br />
    38. 38. Word Boundaries<br />The  shorthand character class matches…<br /><ul><li> position before the first character in a string (like ^)
    39. 39. position after the last character in a string (like $)
    40. 40. between two characters where one is a word character and the other is not</li></ul>4<br />We’ve got 4 orders for 44 lbs of C4<br />
    41. 41. Word Boundaries<br />The B shorthand character class is the negated word boundary – any position between to word characters or two non-word characters.<br />BatB<br />vacation evacuation at that<br />time ate my evaluation<br />
    42. 42. Alternation<br />The pipe symbol delimits two or more character classes that can both match.<br />cat|dog<br />A cat and dog are expected to follow<br />the dogma that their presence with one<br />another leads to catastrophe.<br />
    43. 43. Alternation<br />Alternations include any character classes.<br />cat|dog<br />A cat and dog are expected to follow<br />the dogma that their presence with one<br />another leads to catastrophe.<br />
    44. 44. Alternation<br />Use parenthesis to group alternating matches when you want to limit the reach of alternation.<br />(cat|dog)<br />A cat and dog are expected to follow<br />the dogma that their presence with one<br />another leads to catastrophe.<br />
    45. 45. Eagerness<br />Eagerness causes the order of alternations to matter.<br />and|android<br />A robot and an android fight. The ninja wins.<br />
    46. 46. Greediness<br />Greediness means that the engine will always try to match as much as possible.<br />anS+<br />A robot and an android fight. The ninja wins.<br />
    47. 47. Laziness<br />Laziness, or reluctant, modifies a repetition operator to only match as much as it needs to.<br />anS+?<br />A robot and an android fight. The ninja wins.<br />
    48. 48. Limiting Repetition<br />You can limit repetition with curly braces.<br />d{2,4}<br />1 111111111 11111<br />
    49. 49. Limiting Repetition<br />The second number can be omitted to mean infinite.<br />Essentially {0,} is the same as * and {1,} same as +.<br />d{2,}<br />1 11111111111111<br />
    50. 50. Limiting Repetition<br />The a single number can be used to match an exact number of times.<br />d{4}<br />1 11 111 1111 11111<br />
    51. 51. Back References<br />Parenthesis around a character set groups those characters and creates a back reference.<br />([ai]).1.1<br />The magician said abracadabra!<br />
    52. 52. Named Groups<br />Named groups let you reference matched groups by their name rather than just index.<br />(?&lt;vowel&gt;[ai]).k&lt;vowel&gt;.1<br />The magician said abracadabra!<br />
    53. 53. Negative Lookahead<br />Negative lookaheads match something that is not there.<br />q(?!u)<br />Qatar is home to quite a lot of Iraqi citizens, but is not a city in Iraq<br />
    54. 54. Positive Lookahead<br />Positive lookaheads match something that is there without having that group included in the match.<br />q(?=u)<br />Qatar is home to quite a lot of Iraqi citizens, but is not a city in Iraq<br />
    55. 55. Positive & Negative Lookbehind<br />Lookbehinds are just like lookaheads, but working backwards.<br />(?&lt;=a)q<br />Qatar is home to quite a lot of Iraqi citizens, but is not a city in Iraq<br />
    56. 56. Resources<br />Lots of web pages<br /><br />“Mastering Regular Expressions”<br /> by Jeffrey Friedl<br /><br />