Essential Guide To Regular Expressions: Tools and Tutorials

Advertisement

Regular expressions are an essential part of any programmer’s toolkit. They can be very handy when you need to identify, replace or modify text, words, patterns or characters. In a nutshell: regular expressions (regex) are like a Swiss army knife for modifying strings of just about anything. Need to make your site URLs look pretty? Use regex. Need to remove all punctuation from a sentence? Definitely use regex. The uses for regular expressions are almost limitless.

Regular expressions are something that you’ll come across at least once in your development cycle, whether you’re just trying to modify an .htaccess file to make clean URLs, or something much more advanced like filtering RSS feeds or other data. Here are some resources to get you well on your way to mastering regex.

Getting Started

Just dipping your feet into regex? Here are a few must-read resources to get you started with the basics.

The Absolute Bare-Minimum Every Programmer Should Know About Regular Expressions1
A simple and direct article that outline some of the main “characters” in regular expressions.

Screenshot2

Demystifying Regular Expressions853
In this article a simple usage of regular expressions is described. Its intention is to bring users to try the most powerful search and replace paradigm available and hopefully start using it.

Regular Expression Quickstart4
A primer for grasping some of the basics of regex, pieced together in an easy-to-read format.

Screenshot5

Using Regular Expressions with PHP6
A brief overview of how to use regex syntax with PHP.

Learning to Use Regular Expressions7
Each section of this article has a bit of code on the left for reference while you’re reading what the code actually does on the right side of the page.

Regular Expressions – User guide8
A very detailed and comprehensive introduction to regular expressions, with numerous examples and references.

PHP Freaks: Regular Expressions9
Another detailed introduction to the basics of regular expressions; the article also describes regex concepts such as metacharacters, greediness, lazy match, pattern modifiers and others.

MSDN’s Introduction to Regular Expressions (Scripting)10
These sections introduce the concept of regular expressions and explain how to create and use them.

Regular Expressions Cheat Sheet11
A one-page reference sheet. It is a guide to patterns in regular expressions, and is not specific to any single language. Available in PDF and PNG.

Screenshot12

Visibone Regular Expressions Cheat Sheet13
A quick reference cheat sheet (only .png) for regular expressions for JavaScript.

Screenshot14

Perl Regular Expression Quick Reference15 (pdf) and Perl Regular Expression Quick Reference Card16 (pdf)

Comparison of Regular Expression Engines17
Wikipedia has a helpful comparison of regular expression libraries for quite a few languages. The page also has a table of languages that come with regular expression support, and the differences between them.

Regular Expressions in Ruby and Rails18
Regular expressions in Rails are bracketed by forward-slash, so a regular expression looks like this: /[0-9]*/. You can put all your usual modifiers after the second slash (such as i for case-insensitivity). Gone are other programming languages’ ways of dealing with regular expressions as a string!

Comprehensive Guides

These guides are a little more complex than the previously mentioned starter guides. Perfect for advanced programmers and those wanting to really dig into regular expression functionality.

Crucial Concepts Behind Advanced Regular Expressions19
an introduction to advanced regular expressions, with eight commonly used concepts and examples. Each example outlines a simple way to match patterns in complex strings. If you do not yet have experience with basic regular expressions, have a look at this article20 to get started. The syntax used here matches PHP’s Perl-compatible regular expressions.

Regex Tutorial21
This tutorial is a step-by-step teaching tool to learn every aspect of regular expression usage. It’s best to go through the tutorial top to bottom, as each section builds upon the last.

Screenshot22

Regular Expression – User Guide23
This user guide comes with a soft beginning and goes on to quickly cover most everything about regex. The guide is clean and concise, and packed with code examples.

Screenshot24

perlretut25
An incredible tutorial for those wanting to learn regex with Perl syntax. The tutorial is quite detailed, and is quite massive in size. Yet it’s an authoritative resource for anyone wanting to learn regular expressions from top to bottom.

Screenshot26

Regular Expressions Resources27
This growing collection of resources related to regular expressions includes references to various tools and books.

Regex Tools28
A selection of .NET tools for working with regular expressions.

Extreme regex foo: what you need to know to become a regular expression pro29
In this article you’ll learn about greedy vs. lazy quantifiers, non-capturing parenthesis, pattern modifiers, character and class shorthands as well as positive and negative lookahead.

Practical Regular Expressions

Telephone numbers (via Matt8335343130)
Number in the following form: (###) ###-####

$string = "(232) 555-5555"; 
if (preg_match('/^(?[0-9]{3})?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/', $string)) {  
echo "This is a valid phone number."; 
}

Postal codes (via Matt8335343130)

$string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) { 
echo "This is a valid postal code.";
}

Matching a user name (via immike.net3332)

function validate_username( $username ) {
  if(preg_match('/^[a-zA-Z0-9_]{3,16}$/', $_GET['username'])) {
    return true;
  }
  return false;
}

Matching an XHTML/XML tag (via immike.net3332)

function get_tag( $tag, $xml ) {
  $tag = preg_quote($tag);
  preg_match_all('{<'.$tag.'[^>]*>(.*?).'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);

  return $matches[1];
}

URL validation (via Matt8335343130)

$szString = "http://www.talkPHP.com";
if (preg_match('/^(http|https|ftp)://([w]*).([w]*).(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)(.[a-z]{1,3})?z/i', $szString))
    echo "This is a valid URL";

Emails (via Matt8335343130)

$string = "first.last@domain.co.uk";  
if (preg_match( 
'/^[^W][a-zA-Z0-9_]+(.[a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+(.[a-zA-Z0-9_]+)*.[a-zA-Z]{2,4}$/', 
$string)) {  
echo "This is a valid e-mail.";

Valid credit card number (JavaScript, via ntt.cc36)

	function luhn (cc) {
   var sum = 0;
   var i;
 
   for (i = cc.length - 2; i >= 0; i -= 2) {
      sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
   }
   for (i = cc.length - 1; i >= 0; i -= 2) {
      sum += parseInt (cc.charAt (i), 10);
   }
   return (sum % 10) == 0;
}

Regular Expressions That Are Often Needed in Practice37
Dozens of useful regex-patterns that are often used in programming of web-applications.

Screenshot38

10+ Useful JavaScript Regular Expression Functions39
General JavaScript-based regular expressions for common tasks such as checking if a string is non-blank, if it is a decimal number, if it is currency etc.

RegExLib.com40
The Internet’s first regular expression library. Complete with 2,511 expressions from over 1,500 contributors. You can search and find nearly any pattern matching snippet that you might need for a web project.

Regex Tools

regex online tester41
Regex allows you to test your regular expressions in different types of data in a variety of ways. For instance, you can directly check how your regular expressions are applied to a given web-page (URL) or text. History stores all the regular expressions you’ve created with the tool, so you can use a roll back once you’ve modified the expression in an incorrect way. Regex patterns, filters and modifiers help you to build the regular expression and test it immediately in the same window. Basic knowledge about regular expressions is required to use the tool.

Screenshot42

The Regulator43
The Regulator is an advanced, free regular expressions testing and learning tool that allows you to build and verify a regular expression against any text input, file or web, and displays matching, splitting or replacement results within an easy to understand, hierarchical tree. You can let the tool generate the code in VB.NET and C#.

Regular Expression Tester Firefox Plugin44
This Firefox plugin offers developers functions for testing their regular expressions. The tool includes options like case sensitive, global and multi line search, color highlighting of found expressions and of special characters, a replacement function incl. backreferences, auto-closing of brackets, testing while writing and saving and managing of expressions.

Screenshot45

html2regexp – Regular Expression Generator for HTML Element46
html2regexp is a ruby program of generating regular expressions for extracting HTML elements.

reWork47
ReWork is a regular expression workbench. Type a regular expression into the “pattern” field, and a string to match it against into “input”. The results area updates as you type. You can search, replace, split, scan, parse and generate the graph (FSA, Finite-State Automation) that corresponds to the regular expression.

RegExr48
RegExr is an online regular expression testing and builder. You can play with regex in a helpful environment and make sure your syntax is correct before pushing it live.

Screenshot49

The Regex Coach50
A cross-platform downloadable tool that teaches you about regular expressions in an interactive environment, all from your desktop.

Screenshot51

Rubular52
An online regular expression tester for the Ruby language.

Rex V – Regular Expression eValuator53
This tool is a Regular Expression evaluator for the regular expression systems PHP PCRE, PHP Posix and Javascript.

Flex 3 Regualr Expression Explorer54
This tool provides with popular regular expressions submitted by the community and also lets you try out a regular expression on a test input.

Screenshot55

regexpal56
An interactive javascript regular expression tester. You can also host the tester on your own server with the open source version57 of regexpal.

Screenshot58

Txt2re59
A regex generator that uses a color-based table for visual cues to help you write regular expressions more efficiently.

Screenshot60

reAnimator: Regular Expression FSA Visualizer61
A handy tool to help you see what the regex expression will match against a set of text. You can read more about the service at the reAnimator’s launch post62.

Screenshot63

Javascript Regular Expression Validator64
A helpful regex tester for Javascript that also shows the regular expression library alongside the tester. A simple but very powerful tool.

Screenshot65

RegEx Buddy66
RegexBuddy is a powerful regex tester and builder. You can create regular expressions, study complex regexes written by others, quickly test any regex on sample strings and files, preventing mistakes on actual data. You can also debug without guesswork by stepping through the actual matching process. Besides, the tool generates source code snippets automatically adjusted to the particulars of your programming language. You can also GREP (search-and-replace) through files and folders and integrate RegexBuddy with your favorite searching and editing tools for instant access. Windows only.

Screenshot67

Besides, one of the most useful features of RegEx Buddy is it’s plain English regex tree that makes it easy to understand exactly what a regular expression does – step by step.

Screenshot68

Expreso69
Expresso is a free award winning regular expression development tool. You can build complex regular expressions by selecting components from a palette and test expressions against real or sample input data. The tool can generate Visual Basic, C#, or C++ code and displays all matches in a tree structure, showing captured groups, and all captures within a group. You can also maintain and expand a library of frequently used regular expressions and use a builder and an analyzer to create and test your expressions. Registration is required. Win only.

JavaScript Regex Generator70
An attempt at making a user-friendly regex generator. A little buggy in IE. Currently limited to 7 groups and no support for negating character classes.

Screenshot71

Regex Screencasts

For those wanting to learn regular expressions visually, here are a few excellent screencasts.

Learning Regular Expressions (Video Tutorial and Cheatsheet)72
A screencast with emphasis on how to use regex with E Text Editor73.

A Crash-Course In Regular Expressions74
An introductory crash-course by Jeffrey Way. A little bit outdated, but still useful tutorial that shows how to use regular expressions to check if an e-mail is valid or not. “To a novice web developer, regular expressions look like the most scary thing on the planet. Who could possibly dismantle such a block of code and decipher its meaning? Luckily, its bark is much worse than its bite. You’ll quickly find that regular expressions are rather straight-forward and easy to understand – once you learn the syntax.”

Screenshot75

Regular Expressions for Dummies76
An introductory screencast with a quiz at the end to see what you’ve learned.

Screenshot77

Regex for Dummies: Day 278
Build off of the first ThemeForest screencast79 by learning about matching.

Screenshot80

Regular expressions (the series)81
A 5-part series on the basics of regular expressions.

Regular Expression Tutorials

PHP Regular Expression Examples82
Many different code examples for possible uses of regular expressions with PHP. A few that might be helpful: processing credit cards, dates, email addresses, and many more.

Screenshot83

PHP regular expression tutorial84
This article explains how to use regular expressions in PHP and provides simple and advanced examples of common regex-patterns.

Demystifying Regular Expressions853
Regular expressions on the surface appear pretty complex. Not only does the language look rather odd, but it also requires logic beyond just following protocols. This article helps to take away some of the stigma some might have with regex in an easy-to-follow guide with examples.

The Joy of Regular Expressions [1]86
This Sitepoint tutorial uses simple examples that don’t include incoherent demo strings like “aabbcc” to show how regex really works. The article covers all of the core concepts like exact matching, positive matching, pattern modifiers and more.

Screenshot87

The Joy or Regular Expressions [2]88
This second regex tutorial by Sitepoint provides plenty of useful examples like how to find images with .jpg extensions, and even finding xss security holes in your code with regex.

Screenshot89

Introductory Guide to Regular Expressions90
A quick guide to the basics of spotting patterns in regex, complete with a simple example of a javascript regular expression with forms.

Screenshot91

Know Your Regular Expressions92
IBM has an excellent write-up on how to use regular expressions across UNIX applications.

Screenshot93

Regular Expressions: Now You Have Two Problems94
Jeff Atwood (co-founder of the excellent Stackoverflow95), show some best practices when using regular expressions. Knowing where and when to use regex is sometimes tricky, and Jeff outlines some tips on how to use regular expressions effectively.

Screenshot96

Footnotes

  1. 1 http://immike.net/blog/2007/04/06/the-absolute-bare-minimum-every-programmer-should-know-about-regular-expressions/
  2. 2 http://immike.net/blog/2007/04/06/the-absolute-bare-minimum-every-programmer-should-know-about-regular-expressions/
  3. 3 http://www.linuxforums.org/applications/demystifying_regular_expressions.html
  4. 4 http://www.regular-expressions.info/quickstart.html
  5. 5 http://www.regular-expressions.info/quickstart.html
  6. 6 http://www.webcheatsheet.com/php/regular_expressions.php
  7. 7 http://gnosis.cx/publish/programming/regular_expressions.html
  8. 8 http://www.zytrax.com/tech/web/regex.htm
  9. 9 http://www.phpfreaks.com/content/print/126
  10. 10 http://msdn.microsoft.com/en-us/library/6wzad2b2(VS.85).aspx
  11. 11 http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
  12. 12 http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
  13. 13 http://www.visibone.com/regular-expressions/
  14. 14 http://www.visibone.com/regular-expressions/
  15. 15 http://www.mnlab.cs.depaul.edu/~ehab/Courses/TDC568/resources/PerlQuickRef.pdf
  16. 16 http://refcards.com/docs/trusketti/perl-regexp/perl-regexp-refcard-a4.pdf
  17. 17 http://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines
  18. 18 http://www.railsrocket.com/articles/regular-expressions-in-ruby-and-rails
  19. 19 http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/
  20. 20 http://www.lateralcode.com/regular-expressions/
  21. 21 http://www.regular-expressions.info/tutorialcnt.html
  22. 22 http://www.regular-expressions.info/tutorialcnt.html
  23. 23 http://www.zytrax.com/tech/web/regex.htm
  24. 24 http://www.zytrax.com/tech/web/regex.htm
  25. 25 http://perldoc.perl.org/perlretut.html
  26. 26 http://perldoc.perl.org/perlretut.html
  27. 27 http://regexlib.com/Resources.aspx
  28. 28 http://www.larkware.com/RegexTools.html
  29. 29 http://immike.net/blog/2007/06/21/extreme-regex-foo-what-you-need-to-know-to-become-a-regular-expression-pro/
  30. 30 http://www.talkphp.com/advanced-php-programming/1612-8-practical-php-regular-expressions.html
  31. 31 http://www.talkphp.com/advanced-php-programming/1612-8-practical-php-regular-expressions.html
  32. 32 http://immike.net/blog/2007/04/06/5-regular-expressions-every-web-programmer-should-know/
  33. 33 http://immike.net/blog/2007/04/06/5-regular-expressions-every-web-programmer-should-know/
  34. 34 http://www.talkphp.com/advanced-php-programming/1612-8-practical-php-regular-expressions.html
  35. 35 http://www.talkphp.com/advanced-php-programming/1612-8-practical-php-regular-expressions.html
  36. 36 http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html
  37. 37 http://www.codeproject.com/KB/aspnet/All_Regular_Expression.aspx
  38. 38 http://www.codeproject.com/KB/aspnet/All_Regular_Expression.aspx
  39. 39 http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html
  40. 40 http://regexlib.com/
  41. 41 http://www.regex-tester.de/en,regex.html
  42. 42 http://www.regex-tester.de/en,regex.html
  43. 43 http://tools.osherove.com/CoolTools/Regulator/tabid/185/Default.aspx
  44. 44 https://addons.mozilla.org/en-US/firefox/addon/2077
  45. 45 https://addons.mozilla.org/en-US/firefox/addon/2077
  46. 46 http://llamerada.sakura.ne.jp/html2regexp/index.html
  47. 47 http://osteele.com/tools/rework/
  48. 48 http://gskinner.com/RegExr/
  49. 49 http://gskinner.com/RegExr/
  50. 50 http://www.weitz.de/regex-coach/
  51. 51 http://www.weitz.de/regex-coach/
  52. 52 http://www.rubular.com/
  53. 53 http://rexv.org/
  54. 54 http://ryanswanson.com/regexp/#start
  55. 55 http://ryanswanson.com/regexp/#start
  56. 56 http://regexpal.com/
  57. 57 http://code.google.com/p/regexpal/
  58. 58 http://regexpal.com/
  59. 59 http://txt2re.com/
  60. 60 http://txt2re.com/
  61. 61 http://osteele.com/tools/reanimator/
  62. 62 http://osteele.com/archives/2006/02/reanimator
  63. 63 http://osteele.com/tools/reanimator/
  64. 64 http://tools.netshiftmedia.com/regexlibrary/
  65. 65 http://tools.netshiftmedia.com/regexlibrary/
  66. 66 http://www.regexbuddy.com/
  67. 67 http://www.regexbuddy.com/
  68. 68 http://www.regexbuddy.com/
  69. 69 http://www.ultrapico.com/Expresso.htm
  70. 70 http://www.jslab.dk/tools.regex.php
  71. 71 http://www.jslab.dk/tools.regex.php
  72. 72 http://www.e-texteditor.com/blog/2007/regular_expressions_tutorial
  73. 73 http://e-texteditor.com/
  74. 74 http://blog.themeforest.net/tutorials/a-crash-course-in-regular-expressions/
  75. 75 http://blog.themeforest.net/tutorials/a-crash-course-in-regular-expressions/
  76. 76 http://blog.themeforest.net/screencasts/regular-expressions-for-dummies/
  77. 77 http://blog.themeforest.net/screencasts/regular-expressions-for-dummies/
  78. 78 http://blog.themeforest.net/screencasts/regex-for-dummies-day-2/
  79. 79 http://blog.themeforest.net/screencasts/regular-expressions-for-dummies/
  80. 80 http://blog.themeforest.net/screencasts/regex-for-dummies-day-2/
  81. 81 http://www.videophpblog.com/2008/12/10/regular-expressions-the-series/
  82. 82 http://www.roscripts.com/PHP_regular_expressions_examples-136.html
  83. 83 http://www.roscripts.com/PHP_regular_expressions_examples-136.html
  84. 84 http://www.phpf1.com/tutorial/php-regular-expression.html
  85. 85 http://www.linuxforums.org/applications/demystifying_regular_expressions.html
  86. 86 http://www.sitepoint.com/blogs/2006/09/26/the-joy-of-regular-expressions-1/
  87. 87 http://www.sitepoint.com/blogs/2006/09/26/the-joy-of-regular-expressions-1/
  88. 88 http://www.sitepoint.com/blogs/2006/09/27/the-joy-of-regular-expressions-2/
  89. 89 http://www.sitepoint.com/blogs/2006/09/27/the-joy-of-regular-expressions-2/
  90. 90 http://javascriptkit.com/javatutors/re.shtml
  91. 91 http://javascriptkit.com/javatutors/re.shtml
  92. 92 http://www.ibm.com/developerworks/aix/library/au-regexp/?S_TACT=105AGX59&S_CMP=HP&ca=dgr-lnxw57unixexpr
  93. 93 http://www.ibm.com/developerworks/aix/library/au-regexp/?S_TACT=105AGX59&S_CMP=HP&ca=dgr-lnxw57unixexpr
  94. 94 http://www.codinghorror.com/blog/archives/001016.html
  95. 95 http://www.stackoverflow.com
  96. 96 http://www.codinghorror.com/blog/archives/001016.html

↑ Back to topShare on Twitter

Glen Stansberry is the editor at Web Jackalope, a blog about creative Web development.

Advertising
  1. 1

    Brian Temecula

    June 1, 2009 2:44 pm

    I use RegexBuddy, and it is awesome! I tend to forget regex, because I am not using it all the time, but with RegexBuddy, I can do what I need to do easily.

    0
  2. 2

    Awesome! Thank you!

    0
  3. 3

    useful and time saver. thank you.

    0
  4. 4

    This is great! I’ve been looking for something like this for a long time. One of the best Smashing articles in quite a while. Thanks!

    0
  5. 5

    I can never fully wrap my head around regular expressions. Excellent list of resources to help me figure them out a bit more.

    An app I didn’t see listed above was Reggy (here) for OS X. Very handy for figuring out if you’re patterns match.

    0
  6. 6

    it is awesome! Thx very much

    0
  7. 7

    Jakub Nesetril

    June 1, 2009 4:58 pm

    For some more advanced topics on Regular Expressions, feel free to check out on SlideShare the slides from my Advanced RE redux talk.

    0
  8. 8

    Do you have anything about RegExp for XAML ??? It could be very very useful to get some of info about it.

    0
  9. 9

    Awesome!!! This will definitely help me to push the folks to learn regexp!

    Thanx

    0
  10. 10

    An Excellent resource
    When I started reading this article I thought Ive seen stuff like this in many places but halfway through I realized that like most of Smashing’s articles, this one was bookmark worthy :-)
    Thanks!!

    0
  11. 11

    Niklas Sonnenschein

    June 1, 2009 9:10 pm

    I hate regexp, but with your article it’s very easy! Thanks a lot!

    0
  12. 12

    Simple on-line servise for regular expressions check

    0
  13. 13

    Nice resource. Thanks.

    0
  14. 14

    RegexBuddy is all you really need to get started with regular expressions. It makes them so easy to use. Seriously could not imagine dealing with regexes without it.

    0
  15. 15

    Wonderful post, was seeking for it for a long time. Thanks!

    0
  16. 16

    Mats Taraldsvik

    June 2, 2009 12:30 am

    There’s also ‘Mastering Regular Expressions’ – one of my favourite O’Reilly books. :)

    0
  17. 17

    Jean-Baptiste Jung

    June 2, 2009 12:47 am

    Excellent post. Regular expression have always been a pain for me so I think I have to work lots with that post ;)

    0
  18. 18

    brilliant timing! smash and grab stuff!

    0
  19. 19

    nice article, i’d need a helpful answer if anyone’s up to it please… what win application (possibly freeware) can i use to do a particular replace action on some html files. i need to replace one part of a line in my html files with a part of another line in the same html file (both part change with each html file and i already made proper regex expressions to target both across all files). the problem i’m having with the app i’m currently using for search/replace operations is that the syntax for the replace field is too restrictive in that i can’t enter a classic regex expression, but just use variables that deal only with parts of what the regex expression in the search field has returned. this obviously means that the replace part cannot be a completely independent part of the document, but only a constant or a modified version of what the search has produced. tia for any pointers.

    0
  20. 20

    Great post as usual.
    Thanks

    0
  21. 21

    @regquest – if you have access to Dreamweaver at all, then you can plug your HTML files into a project, and then have Dreamweaver do a project-wide search on your regexp.

    0
  22. 22

    Omg, thanks for this list. It really has everything one needs to learn this sh*t.

    Thank you!

    0
  23. 23

    Regular expressions are great for validation, but also for find & replace operations. Dreamweaver and TextWrangler (mac) have great regular expression handling. Using these can save a tonne of time in development.

    0
  24. 24

    Awsome!!! Это СУПЕР!!!! Спасибо! Thank u! Gracias!

    0
  25. 25

    Any author will hopefully recommend his own book. So at the risk of being self-serving, I’d like to mention that I wrote my books specifically for developers who want to do specific tasks and learn how each expression works, bit-by-bit. In my books, “Regular Expression Recipes: A Problem-Solution Approach” and “Regular Expression Recipes for Windows Developers…” I provide 100 common tasks (validating e-mail addresses, phone numbers, HTML entities, CSV field parsing, etc.) and I walk through each expression, telling the reader how each character functions in the expression to make it work.

    0
  26. 26

    Very useful list as usual. Thanks!

    0
  27. 27

    The email address regular expression listed above is not correct – it’s missing many of the allowed characters from RFC 5322, which will cause validation problems for many users.

    0
  28. 28

    interesting stuff

    0
  29. 29

    yeah this is a great post

    0
  30. 30

    Great article and great collection. This will definitely going to help me while validating values. Often i forget regex coz I dont use much. But will learn and be prepared.

    Thank you so much

    0
  31. 31

    LaunchTulsa.com

    June 2, 2009 10:23 am

    The ‘Practical Regular Expressions’ will be used the most by us.

    Great post.

    0
  32. 32

    Here’s a free yet very extensive tool: http://www.radsoftware.com.au/regexdesigner/

    0
  33. 33

    Not sure that the Matching a user name is correct.

    david37 is usually a valid username whereas 37david is not. Both of these would pass your test.

    There are lots of advantages to forcing a start character in a username for example take the following two addresses used in an API.

    /user/david37/
    /user/109/

    If we force a letter then instantly we know 109 is a user ID not a username.

    0
  34. 34

    Awesome! Thank you!

    0
  35. 35

    Hi there

    Truly enjoyed this post. I only use regex occasionally and tend to forget the ropes in-between usage.

    This page will definitely sit high in my bookmark list 

    Thanks again

    0
  36. 36

    Jehzeel Laurente

    June 3, 2009 1:47 am

    This article is really helpful, specially to regexp noob like me. I just downloaded the PDF from added bytes. :)

    0
  37. 37

    The email address sample pattern on the PDF cheat sheet is INCORRECT. For instance:

    it will correctly identify:
    foo{at}bar.baz

    But will fail on the following:
    foo{at}bar.baz.edu
    foo.bar{at}baz.edu
    foo.bar{at}baz.qux.uk

    The example submitted via “matt83″ under the heading “practical regular expressions” appears to be a proper implementation, but AFAICT will does not test double periods, and other valid-character-yet-invalid sequences

    0
  38. 38

    hehe, sorry about the unintended links in the above (post was held for moderation and not editable by me). HOVER for the intended text.

    0
  39. 39

    Daniel Costalis

    June 4, 2009 12:53 am

    This guy is a hack. He is not an author, but a compiler of others works, and doesn’t even check theirs before posting. I’m sure he doesn’t understand regex at all, considering the last article of his I read was “20 AJAX effects you should know about” where nothing related to AJAX was “written” about or tested.

    This is something that was bookmarked and Dugg before being read all the way through, I’m sure. just go to http://www.regular-expressions.info for any regex info you could ever want.

    0
  40. 40

    Better RegEx for Phone number validation : (###) ###-####
    /^[(]?[d]{3}[)]?[-. ]?[d]{3}[-. ]?[d]{4}$/

    @rpsms U can use this RegEx for E-mail validation
    /^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,5})$/

    0
  41. 41

    Steffan Nicholson

    June 5, 2009 7:43 am

    For the UK visitors… the following validates UK postcodes (including British Forces Post Office ,UK Overseas Territories, and the Girobank postcode which breaks the rules) without the need for lookarounds (which aren’t supported in all engines):

    ^([A-PR-UWYZ](?:d[dA-HJKSTUW]?|[A-HK-Y]d[dABEHMNPRV-Y]?) d[ABD-HJLNP-UW-Z]{2}|BFPO (c/o (?=d{1,3}$))?[1-9]d{0,3}|AI-2640|(ASCN|BBND|BIQQ|FIQQ|PCRN|SIQQ|STHL|TDCU|TKCA) 1ZZ|GIR 0AA)$

    0
  42. 42

    Steffan Nicholson

    June 5, 2009 8:02 am

    As Krues8dr observed email validation has to be handled well unless you only do the most rudimentary of checks — I haven’t got around to revising for RFC 5322 but have previously written expressions for RFC 822 (STD 0011) and RFC 2822.

    The following is for 2822, the only things lacking (other than TLD specific restrictions; provision for the inclusion of a display-name; General-address-literal support) are length restrictions (maximum of 64 characters in total) for the local-part(s) and (maximum of 255 characters in total) for the domain which—are only limits in respect of guaranteed support within SMTP implementations, and—would require the use of lookarounds or a second test (as you cannot both allow multiple word sections in the local-part or domain and simultaneously restrict the overall lengths of these without lookarounds):

    ^(?:[^()@,;:\".[]x00-x20u007F-uFFFF]+(?:.[^()@,;:\".[]x00-x20u007F-uFFFF]+)*|”(?:(?:(?:[t ]*rn)?[t ]+)?(?:[^x00tnr "\u0080-uFFFF]|\[^nru0080-uFFFF]))*(?:(?:[t ]*rn)?[t ]+)?”)@(?:(?:[a-zA-Z](?:[a-zA-Zd-]{0,61}[a-zA-Zd])?.)+[a-zA-Z]{2,}|[(?:IPv6:(?:[1-9a-fA-F][da-fA-F]{1,3}|[da-fA-F][1-9a-fA-F][da-fA-F]{0,2}|[da-fA-F]{0,2}[1-9a-fA-F][da-fA-F]|[da-fA-F]{0,3}[1-9a-fA-F]):(?:(?:[da-fA-F]{1,4}:){6}|(?:[da-fA-F]{1,4}:){4}:|(?:[da-fA-F]{1,4}:){3}:(?:[da-fA-F]{1,4}:)?|(?:[da-fA-F]{1,4}:){2}:(?:[da-fA-F]{1,4}:){0,2}|(?:[da-fA-F]{1,4}:):(?:[da-fA-F]{1,4}:){0,3}|:(?:[da-fA-F]{1,4}:){0,4})(?:[1-9a-fA-F][da-fA-F]{1,3}|[da-fA-F][1-9a-fA-F][da-fA-F]{0,2}|[da-fA-F]{0,2}[1-9a-fA-F][da-fA-F]|[da-fA-F]{0,3}[1-9a-fA-F])|(?:(?:(?:0{1,4}:){5}(?:0{1,4}|[fF]{4}):)|(?:IPv6:::(?:[fF]{4}:)?))?(?:25[0-4]|2[0-4]d|1d{2}|[1-9]d?)(?:.(?:25[0-4]|2[0-4]d|1d{2}|[1-9]?d)){2}.(?:25[0-4]|2[0-4]d|1d{2}|[1-9]d?))])$

    The problem with all this is that it would accept mickey@disney.com as being a valid address format but I can bet that’s not your address!

    It is in fact possible to go beyond this though and to extract teh domain and lookup the MX record to verify that they have a mail server, and depending on their configuration you can even query their mail server to check if the mailbox exists — but unless you have them respond to a confirmation email you still won’t know if it is their address.

    0
  43. 43

    Steffan Nicholson

    June 5, 2009 8:20 am

    Oops… the link should just have been the email for mickey@disney.com — like rpsms I was held for moderation and couldn’t edit it out.

    BTW… the domain part of the expression is so large because it allows for IPv4 and IPv6 domain literals, without these the expression would be considerably shorter.

    0
  44. 44

    Julio Fagundes

    June 5, 2009 5:21 pm

    Nice post! I have been search a good online tester ER.
    I found: http://tools.lymas.com.br/regexp_br.php

    So good as you commented.

    0
  45. 45

    The way I got my head around the basics and regex is writing a validation class in php and javascript (same class) and using it to validate, phone numbers, credit cards, addresses, etc… i posted a few below

    basic credit card validation (checks to see if its one of the big cc’s)
    ^((4d{3})|(5[1-5]d{2})|(6011))-?d{4}-?d{4}-?d{4}|3[4,7][ds-]{13}$

    zip code in the format of 12345-1234 or 12345
    ^([0-9]{5}[-][0-9]{4})|([0-9]{5})$

    phone, with area codes in or not in ()’s and number seperators as a space . or -
    ^((d{3})|d{3})(-|.|s)?d{3}(-|.|s)?d{4}$

    addresses can have 1-8 digits for the street number and any number or words in the street name and periods for st. rd. etc
    ^[d]{1,8}s[ws.]*$

    0
  46. 46

    Steffan Nicholson

    June 9, 2009 9:53 am

    Of course ^([0-9]{5}[-][0-9]{4})|([0-9]{5})$ could equally be written as ^d{5}(-d{4})?$ which just goes to show there is always more than one way to write an expression.

    I won’t bother correcting issues with the others as I’m sure some are simply typos as testing would have identified the problems with them as quoted.

    Traditionally I tested in my own engine but I have to say I’ve grown quite accustomed to using expresso of late.

    0
  47. 47

    In the Practical Regular Expressions section. The last example uses the Luhn algorithm for validation of credit-card numbers. This is not in fact a regular expression but simply just javascript code. It should not be included in this list.

    0
  48. 48

    excellent post and very useful please can u send any post relates to perl like this

    0
  49. 49

    Brian Katz - Analytics - VKI

    November 24, 2009 6:57 pm

    Wow! what a resource! Thanks.

    Big fan of RegEx Buddy

    Brian Katz – Analytics – VKI

    0
  50. 50

    Useful information. Fortunate me I discovered your site by accident, and I am shocked why this coincidence didn’t happened in advance! I bookmarked it.

    0
  51. 51

    nice tutorial ..thanks :)
    Try http://tryphpregex.com/ php based online regex editor which helps you test your regular expressions with real-time highlighting of regex match on data input.

    0
  52. 52

    Thank’s.

    Very good list.

    0

↑ Back to top