Your SlideShare is downloading. ×
0
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Introduction to Regular Expressions
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to Regular Expressions

5,297

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 …

^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
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
5,297
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
268
Comments
0
Likes
7
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
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 http://regex.info/blog/2006-09-15/247 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.
  • Transcript

    1. Introduction toRegular Expressions<br />Matt Casto<br />http://google.com/profiles/mattcasto<br />
    2. Introduction toRegular Expressions<br />Matt Casto<br />Quick Solutions<br />http://google.com/profiles/mattcasto<br />
    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. 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 />
    5. 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 />
    6. 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 />
    7. History<br />grep<br />Global Regular Expression Print<br />
    8. History<br />Henry Spencer<br />Wrote the regex library which is what Perl and Tcl languages used for regular expressions.<br />
    9. Why Should You Care?<br />Example: finding duplicate words in a file.<br />Requirements:<br /><ul><li> Output lines that contain duplicate words
    10. Find doubled words that expand lines
    11. Ignore capitalization differences
    12. Ignore HTML tags</li></li></ul><li>
    13. 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 />
    14. 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 />
    15. 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 />
    16. Literal Characters<br />Literals are case sensitive – capitalization matters!<br />regex<br />j<br />Jack is a boy<br />NOT a match<br />
    17. Special Characters<br />[ ^ $ . | ? * + ( )<br />
    18. 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 />
    19. Special Characters<br />Some characters, such as { and } are only reserved depending on context.<br />if (true) {<br />else if (true) { beep; }<br />
    20. 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 />
    21. Period<br />The period character matches any single character.<br />a.boy<br />Jack is a boy<br />
    22. 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 />
    23. 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 />
    24. 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 />
    25. 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 />
    26. 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 />
    27. 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 />
    28. 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 />
    29. 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 />
    30. 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 />
    31. Anchors<br />The caret anchor matches the position before the first character in a string.<br />^vac<br />vacation evacuation<br />
    32. Anchors<br />The dollar sign anchor matches the position after the last character in a string.<br />tion$<br />vacation evacuation<br />
    33. 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 />
    34. 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 />
    35. Word Boundaries<br />The  shorthand character class matches…<br /><ul><li> position before the first character in a string (like ^)
    36. position after the last character in a string (like $)
    37. 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 />
    38. 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 />
    39. 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 />
    40. 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 />
    41. 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 />
    42. Eagerness<br />Eagerness causes the order of alternations to matter.<br />and|android<br />A robot and an android fight. The ninja wins.<br />
    43. 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 />
    44. 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 />
    45. Limiting Repetition<br />You can limit repetition with curly braces.<br />d{2,4}<br />1 111111111 11111<br />
    46. 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 />
    47. 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 />
    48. 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 />
    49. 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 />
    50. 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 />
    51. 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 />
    52. 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 />
    53. Resources<br />Lots of web pages<br />http://del.icio.us/mattcasto/regex<br />“Mastering Regular Expressions”<br /> by Jeffrey Friedl<br />http://oreilly.com/catalog/9780596528126/<br />

    ×