1. Regular Expression Tutorial
In this tutorial, I will teach you all you need to know to be able to craft powerful time-saving regular expressions. I will start with the most basic concepts, so that you can follow this tutorial even if you know nothing at all about regular expressions yet. But I will not stop there. I will also explain how a regular expression engine works on the inside, and alert you at the consequences. This will help you to understand quickly why a particular regex does not do what you initially expected. It will save you lots of guesswork and head-scratching when you need to write more complex regexes.

What Regular Expressions Are Exactly - Terminology
Basically, a regular expression is a pattern describing a certain amount of text. Their name comes from the mathematical theory on which they are based. But we will not dig into that. Since most people including myself are lazy to type, you will usually find the name abbreviated to regex or regexp. I prefer regex, because it is easy to pronounce the plural "regexes". In this book, regular expressions are printed guillemots: «regex». They clearly separate the pattern from the surrounding text and punctuation. This first example is actually a perfectly valid regex. It is the most basic pattern, simply matching the literal text „regex”. A "match" is the piece of text, or sequence of bytes or characters that pattern was found to correspond to by the regex processing software. Matches are indicated by double quotation marks, with the left one at the base of the line. «\b[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z0-9._%-]{2,4}\b» is a more complex pattern. It describes a series of letters, digits, dots, percentage signs and underscores, followed by an at sign, followed by another series of letters, digits, dots, percentage signs and underscores, finally followed by a single dot and between two and four letters. In other words: this pattern describes an email address. With the above regular expression pattern, you can search through a text file to find email addresses, or verify if a given string looks like an email address. In this tutorial, I will use the term "string" to indicate the text that I am applying the regular expression to. I will indicate strings using regular double quotes. The term “string” or “character string” is used by programmers to indicate a sequence of characters. In practice, you can use regular expressions with whatever data you can access using the application or programming language you are working with.

Different Regular Expression Engines
A regular expression “engine” is a piece of software that can process regular expressions, trying to match the pattern to the given string. Usually, the engine is part of a larger application and you do not access the engine directly. Rather, the application will invoke it for you when needed, making sure the right regular expression is applied to the right file or data. As usual in the software world, different regular expression engines are not fully compatible with each other. It is not possible to describe every kind of engine and regular expression syntax (or “flavor”) in this tutorial. I will focus on the regex flavor used by Perl 5, for the simple reason that this regex flavor is the most popular

40 one, and deservedly so. Many more recent regex engines are very similar, but not identical, to the one of Perl 5. Examples are the open source PCRE engine (used in many tools and languages like PHP), the .NET regular expression library, and the regular expression package included with version 1.4 and later of the Java JDK. I will point out to you whenever differences in regex flavors are important, and which features are specific to the Perl-derivatives mentioned above.

Give Regexes a First Try
You can easily try the following yourself in a text editor that supports regular expressions, such as EditPad Pro. If you do not have such an editor, you can download the free evaluation version of EditPad Pro to try this out. EditPad Pro's regex engine is fully functional in the demo version. As a quick test, copy and paste the text of this page into EditPad Pro. Then select Edit|Search and Replace from the menu. In the search pane that appears near the bottom, type in «regex» in the box labeled “Search Text”. Mark the “Regular expression” checkbox, unmark “All open documents” and mark “Start from beginning”. Then click the Search button and see how EditPad Pro's regex engine finds the first match. When “Start from beginning” is checked, EditPad Pro uses the entire file as the string to try to match the regex to. When the regex has been matched, EditPad Pro will automatically turn off “Start from beginning”. When you click the Search button again, the remainder of the file, after the highlighted match, is used as the string. When the regex can no longer match the remaining text, you will be notified, and “Start from beginning” is automatically turned on again. Now try to search using the regex «reg(ular expressions?|ex(p|es)?)». This regex will find all names, singular and plural, I have used on this page to say “regex”. If we only had plain text search, we would have needed 5 searches. With regexes, we need just one search. Regexes save you time when using a tool like EditPad Pro. If you are a programmer, your software will run faster since even a simple regex engine applying the above regex once will outperform a state of the art plain text search algorithm searching through the data five times. Regular expressions also reduce development time. With a regex engine, it takes only one line (e.g. in Perl, PHP, Java or .NET) or a couple of lines (e.g. in C using PCRE) of code to, say, check if the user's input looks like a valid email address.


2. Literal Characters
The most basic regular expression consists of a single literal character, e.g.: «a». It will match the first occurrence of that character in the string. If the string is “Jack is a boy”, it will match the „a” after the “J”. The fact that this “a” is in the middle of the word does not matter to the regex engine. If it matters to you, you will need to tell that to the regex engine by using word boundaries. We will get to that later. This regex can match the second „a” too. It will only do so when you tell the regex engine to start searching through the string after the first match. In a text editor, you can do so by using its “Find Next” or “Search Forward” function. In a programming language, there is usually a separate function that you can call to continue searching through the string after the previous match. Similarly, the regex «cat» will match „cat” in “About cats and dogs”. This regular expression consists of a series of three literal characters. This is like saying to the regex engine: find a «c», immediately followed by an «a», immediately followed by a «t». Note that regex engines are case sensitive by default. «cat» does not match “Cat”, unless you tell the regex engine to ignore differences in case.

Special Characters
Because we want to do more than simply search for literal pieces of text, we need to reserve certain characters for special use. In the regex flavors discussed in this tutorial, there are 11 characters with special meanings: the opening square bracket «[», the backslash «\», the caret «^», the dollar sign «$», the period or dot «.», the vertical bar or pipe symbol «|», the question mark «?», the asterisk or star «*», the plus sign «+», the opening round bracket «(» and the closing round bracket «)». These special characters are often called “metacharacters”. If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash. If you want to match „1+1=2”, the correct regex is «1\+1=2». Otherwise, the plus sign will have a special meaning. Note that «1+1=2», with the backslash omitted, is a valid regex. So you will not get an error message. But it will not match “1+1=2”. It would match „111=2” in “123+111=234”, due to the special meaning of the plus character. If you forget to escape a special character where its use is not allowed, such as in «+1», then you will get an error message. All other characters should not be escaped with a backslash. That is because the backslash is also a special character. The backslash in combination with a literal character can create a regex token with a special meaning. E.g. «\d» will match a single digit from 0 to 9.

Special Characters and Programming Languages
If you are a programmer, you may be surprised that characters like the single quote and double quote are not special characters. That is correct. When using a regular expression or grep tool like PowerGREP or the

42 search function of a text editor like EditPad Pro, you should not escape or repeat the quote characters like you do in a programming language. In your source code, you have to keep in mind which characters get special treatment inside strings by your programming language. That is because those characters will be processed by the compiler, before the regex library sees the string. So the regex «1\+1=2» must be written as "1\\+1=2" in C++ code. The C++ compiler will turn the escaped backslash in the source code into a single backslash in the string that is passed on to the regex library. To match „c:\temp”, you need to use the regex «c:\\temp». As a string in C++ source code, this regex becomes "c:\\\\temp". Four backslashes to match a single one indeed. See the tools and languages section in this book for more information on how to use regular expressions in various programming languages.

Non-Printable Characters
You can use special character sequences to put non-printable characters in your regular expression. «\t» will match a tab character (ASCII 0x09), «\r» a carriage return (0x0D) and «\n» a line feed (0x0A). Remember that Windows text files use “\r\n” to terminate lines, while UNIX text files use “\n”. You can include any character in your regular expression if you know its hexadecimal ASCII or ANSI code for the character set that you are working with. In the Latin-1 character set, the copyright symbol is character 0xA9. So to search for the copyright symbol, you can use «\xA9». Another way to search for a tab is to use «\x09». Note that the leading zero is required.

after introducing a new regex token. „a”. . it will try all possible permutations of the regex. First Look at How a Regex Engine Works Internally Knowing how the regex engineworks will enable you to craft better regexes more easily. there are a few versions of these tools that use a regex-directed engine. The engine then proceeds to attempt to match the remainder of the regex at character 15 and finds that «a» matches „a” and «t» matches „t”. you can be certain the engine is regex-directed. The first match is considered good enough. The engine will then try to match the second token «a» to the 5th character. For awk and egrep. will the engine continue with the second character in the text. The engine never proceeds beyond this point to see if there are any “better” matches. egrep. then it is text-directed. The result is that the regex-directed engine will return the leftmost match. If backreferences and/or lazy quantifiers are available. The Regex-Directed Engine Always Returns the Leftmost Match This is a very important point to understand: a regex-directed engine will always return the leftmost match. The reason behind this is that the regex-directed engine is “eager”. At the 15th character in the match. because it merely consists of a sequence of literal characters. Notable tools that use text-directed engines are awk. There are two kinds of regular expression engines: text-directed engines. as does matching the «c» with the space. So it will continue with the 5th: “a”. the engine will start at the first character of the string. You can easily find out whether the regex flavor you intend to use has a text-directed or regex-directed engine. But understanding how the regex engine works will enable you to use its full power and help you avoid common mistakes. There are no other possible permutations of this regex. When applying «cat» to “He captured a catfish for his cat. If the result is „regex not”. the engine knows the regex cannot be matched starting at the 4th character in the match. lex. Again. At that point. respectively. But then. Arriving at the 4th character in the match. This inside look may seem a bit long-winded at certain times.43 3. This fails too. Only if all possibilities have been tried and found to fail. and regex-directed engines. So the regex engine tries to match the «c» with the “e”. can only be implemented in regex-directed engines. The engine is "eager" to report a match. Again. You can do the test by applying the regex «regex|regex not» to the string “regex not”. such as lazy quantifiers and backreferences. This will save you lots of guesswork and head-scratching when you need to write more complex regexes. It will try all possible permutations of the regular expression at the first character. the engine will try to match the first token in the regex «c» to the first character in the match “H”. in exactly the same order. Jeffrey Friedl calls them DFA and NFA engines. MySQL and Procmail. When applying a regex to a string. This is because certain very useful features. flex. In this tutorial. It will help you understand quickly why a particular regex does not do what you initially expected. «c» again matches „c”. «c» fails to match here and the engine carries on. even if a “better” match could be found later. This fails. All the regex flavors treated in this tutorial are based on regex-directed engines. This succeeds too. It will therefore report the first three letters of catfish as a valid match. the engine is regex-directed. I will explain step by step how the regex engine actually processes that token. «c» matches „c”. The entire regular expression could be matched starting at character 15. «t» fails to match “p”. No surprise that this kind of engine is more popular.”. If the resulting match is only „regex”.

44 In this first example of the engine's internals. once you know how the engine works. the way the engine works will have a profound impact on the matches it will find. it is important that you can follow the steps the engine takes in your mind. A text-directed engine would have returned the same result too. But they are always logical and predetermined. our regex engine simply appears to work like a regular text search routine. . Some of the results may be surprising. However. In following examples.

The order of the characters inside a character class does not matter. It will not match the q in the string “Iraq”. but doing so significantly reduces readability. The usual metacharacters are normal characters inside a character class. the order of the characters and the ranges does not matter. Metacharacters Inside Character Classes Note that the only special characters or metacharacters inside a character class are the closing bracket (]). use «[ae]». Find a C-style hexadecimal number with «0[xX][A-Fa-f0-9]+». the backslash (\). To search for a star or plus. Your regex will work fine if you escape the regular metacharacters inside a character class. Character Classes or Character Sets With a "character class". «[0-9a-fA-F]» matches a single hexadecimal digit. also called “character set”. “graey” or any such thing. Find an identifier in a programming language with «[A-Za-z_][A-Za-z_0-9]*». The result is that the character class will match any character that is not in the character class. It will match the q and the space after the q in “Iraq is a country”.45 4. «[0-9a-fxA-FX]» matches a hexadecimal digit or the letter X. «q[^u]» does not mean: “a q not followed by a u”. You could use this in «gr[ae]y» to match either „gray” or „grey”. Again. «[0-9]» matches a single digit between 0 and 9. you need to use negative lookahead: «q(?!u)». It is important to remember that a negated character class still must match a character. Very useful if you do not know whether the document you are searching through is written in American or British English. . such as «sep[ae]r[ae]te» or «li[cs]en[cs]e». Simply place the characters you want to match between square brackets. you can tell the regex engine to match only one out of several characters. negated character classes also match (invisible) line break characters. because it is the “character that is not a u” that is matched by the negated character class in the above regexp. A character class matches only a single character. You can combine ranges and single characters. But we will get to that later. and only the q. You can use more than one range. Indeed: the space will be part of the overall match. case insensitively. even if it is misspelled. «gr[ae]y» will not match “graay”. and do not need to be escaped by a backslash. You can use a hyphen inside a character class to specify a range of characters. If you want the regex to match the q. the caret (^) and the hyphen (-). Unlike the dot. in both strings. Useful Applications Find a word. It means: “a q followed by a character that is not a u”. The results are identical. Negated Character Classes Typing a caret after the opening square bracket will negate the character class. If you want to match an a or an e. use «[+*]».

«\w» stands for “word character”. «[\da-fA-F]» matches a hexadecimal digit. «\d» is short for «[0-9]». «[]x]» matches a closing bracket or an x. or by placing them in a position where they do not take on their special meaning. In most flavors. In all flavors discussed in this tutorial. In most. Some flavors include additional. In all flavors. or right after the negating caret. Exactly which characters it matches differs between regex flavors. To include a caret. In some flavors. while the latter matches „1” (one). or the negating caret. depends on the regex flavor. In EditPad Pro. The best way to find out is to do a couple of tests with the regex flavor you are using. «\s» stands for “whitespace character”. «\s\d» matches a whitespace character followed by a digit. which characters this actually includes. Both «[-x]» and «[x-]» match an x or a hyphen. That is: «\s» will match a space or a tab. The hyphen can be included right after the opening bracket. «[\\x]» matches a backslash or an x. the caret (^) and the hyphen (-) can be included by escaping them with a backslash. the actual character range depends on the script you have chosen in Options|Font. it also includes a carriage return or a line feed as in «[ \t\r\n]». . you can see the characters matched by «\w» in PowerGREP when using the Western script. Again. «[x^]» matches an x or a caret. You can put the closing bracket right after the opening bracket. you have to escape it with another backslash. place it anywhere except right after the opening bracket. «[\s\d]» matches a single character that is either whitespace or a digit. The closing bracket (]). Shorthand Character Classes Since certain character classes are used often. When applied to “1 + 2 = 3”. «[^]x]» matches any character that is not a closing bracket. If you are using the Western script. it includes «[ \t]». and is equivalent to «[0-9a-fA-F]». since it improves readability. In the screen shot. a series of shorthand character classes are available. the former regex will match „ 2” (space two). it will include «[A-Za-z]». for example. Shorthand character classes can be used both inside and outside the square brackets.46 To include a backslash as a character without any special meaning inside a character class. I recommend the latter method. etc. or right before the closing bracket. Negated Shorthand Character Classes The above three shorthands also have negated versions. «\W» is short for «[^\w]» and «\S» is the equivalent of «[^\s]». word characters from other languages may also match. If you are using the Cyrillic script. the underscore and digits are also included. characters with diacritics used in languages such as French and Spanish will be included. rarely used non-printable characters such as vertical tab and form feed. Russian characters will be included. «\D» is the same as «[^\d]».

«[\D\S]» will match any character. That is: «gr[ae]y» can match both „gray” and „grey”. you need to use lookahead and lookbehind. however. whitespace or otherwise. The last regex token is «y». „g” is matched. which can be matched with the following character as well. rather than the class. Let us take a look at that first. We already saw how the engine applies a regex consisting only of literal characters. and „gray” could have been matched in the string. Repeating Character Classes If you repeat a character class by using the «?». and look no further. The engine will fail to match «g» at every step. and fail.47 Be careful when using the negated shorthands inside square brackets. Nothing noteworthy happens for the first twelve characters in the string. The next token in the regex is the literal «r». «([09])\1+» will match „222” but not “837”. But the engine simply did not get that far. it must continue trying to match all the other permutations of the regex pattern before deciding that the regex cannot be matched with the text starting at character 13. The latter will match any character that is not a digit or whitespace. digit. It will return „grey” as the match result. The former. Looking Inside The Regex Engine As I already said: the order of the characters inside a character class does not matter. you will repeat the entire character class. The regex «[0-9]+» can match „837” as well as „222”. «[\D\S]» is not the same as «[^\d\s]». and continue with the next character in the string. When the engine arrives at the 13th character. or is not whitespace. I will explain how it applies a regex that has more than one permutation. Again. will match any character that is either not a digit. The engine has found a complete match with the text starting at character 13. because that is the leftmost match. «gr[ae]y» will match „grey” in “Is his hair grey or gray?”. So it will match „x”. Because a digit is not whitespace. It will first attempt to match «a». «*» or «+» operators. «[ae]» is attempted at the next character in the text (“e”). When applied to the string “833337”. even though we put the «a» first in the character class. The character class gives the engine two options: match «a» or match «e». So the third token. But I digress. I did not yet explain how character classes work inside the regex engine. Below. The engine will then try to match the remainder of the regex with the text. and not just the character that it matched. it will match „3333” in the middle of this string. So it will continue with the other option. . If you want to repeat the matched character. and find that «e» matches „e”. If you do not want that. which matches the next character in the text. But because we are using a regex-directed engine. because another equally valid match was found to the left of it. but not “8”. you will need to use backreferences. and whitespace is not a digit. the leftmost match was returned.

so we do not need to escape it with a backslash. The first tools that used regular expressions were line-based. All regex flavors discussed here have an option to make the dot match all characters. In all programming languages and regex libraries I know.Match(“string”. it is also the most commonly misused metacharacter. Remember that the dot is not a metacharacter inside a character class. In all regex flavors discussed in this tutorial. you simply tick the checkbox labeled “dot matches newline”. the dot will not match a newline character by default. When using the regex classes of the .]\d\d» is a better solution. This is a bit unfortunate. Seems fine at first. I will illustrate this with a simple example. and apply the regular expression separately to each line. «\d\d[. “regex”. the mode where the dot also matches newlines is called "single-line mode". the dot or period is one of the most commonly used metacharacters. the dot is short for the negated character class «[^\n]» (UNIX regex flavors) or «[^\r\n]» (Windows regex flavors). Unfortunately. In RegexBuddy.NET framework./. the first dot matched „5”. and the second matched „7”. and single-line mode only affects the dot. This regex allows a dash. In Perl. such as in Regex.48 5. Other languages and regex libraries have adopted Perl's terminology. . the string could never contain newlines. but we want to leave the user the choice of date separators. Obviously not what we intended. so the dot could never match them. Let's say we want to match a date in mm/dd/yy format. It will match a date like „02/12/03” just fine. Use The Dot Sparingly The dot is a very powerful regex metacharacter. dot and forward slash as date separators. and everything will match just fine when you test the regex on valid data. RegexOptions. without caring what that character is.\d\d. please give it a clearer label like was done in RegexBuddy. like this: m/^regex$/s. Put in a dot. You can activate single-line mode by adding an s after the regex code. The problem is that the regex will also match in cases where it should not match. It allows you to be lazy.Singleline). you activate this mode by specifying RegexOptions. The only exception are newlinecharacters. EditPad Pro and PowerGREP. They would read a file line by line. The effect is that with these tools. Trouble is: „02512703” is also considered a valid date by this regular expression. EditPad Pro or PowerGREP.. because it is easy to mix up this term with “multi-line mode”. The quick solution is «\d\d./. So if you expose this option to your users. In this match. The Dot Matches (Almost) Any Character In regular expressions. This exception exists mostly because of historic reasons. If you are new to regular expressions. So by default. activating single-line mode has no effect other than making the dot match newlines. space.]\d\d[. Multi-line mode only affects anchors.Singleline. Modern tools and languages can apply regular expressions to very large strings or even entire files.\d\d». some of these cases may not be so obvious at first. The dot matches a single character. including newlines.

If you test this regex on “Put a “string” between double quotes”. It matches „99/99/99” as a valid date. If you are parsing data files from a known source that generates its files in the same way every time.*"» seems to do the trick just fine. Our original definition of a double-quoted string was faulty. but the warning is important enough to mention it here as well. «[0-1]\d[. The reason for this is that the star is greedy./. including zero. we have a problem with “string one” and “string two”. Here. We want any number of characters that are not double quotes or newlines between the quotes. How perfect you want your regex to be depends on what you want to do with it. The dot matches any character. You can find a better regex to match dates in the example section. Suppose you want to match a double-quoted string. So the proper regex is «"[^"\r\n]*"». If you are validating user input. We do not want any number of any character between the quotes. Now go ahead and test it on “Houston. The regex matches „“string one” and “string two””. . and the star allows the dot to be repeated any number of times. though it will still match „19/39/99”. we will do the same.]\d\d» is a step ahead. it will match „“string”” just fine. Definitely not what we intended. I will illustrate with an example. it has to be perfect. In the date-matching example. Sounds easy. We can have any number of any character between the double quotes. Use Negated Character Sets Instead of the Dot I will explain this in depth when I present you the repeat operators star and plus. so «".][0-3]\d[/. our last attempt is probably more than sufficient to parse the data without errors. we improved our regex by replacing the dot with a character class.” Ouch. Please respond.49 This regex is still far from perfect.

Anchors are a different breed. «$» matches right after the last character in the string. Therefore. after or between characters.Match(“string”. If you use the code if ($input =~ m/\d+/) in a Perl script to see if the user entered an integer number. They do not match any character at all. and regex tools like PowerGREP. When Perl reads from a line from a text file. The correct regex to use is «^\d+$». matched by «^». It is easy for the user to accidentally type in a space. So before validating input.Multiline). «^» can then match at the start of the string (before the “f” in the above string). such as in Regex. In every programming language and regex library I know. They can be used to “anchor” the regex match at a certain position. it is often desirable to work with lines. Handy use of alternation and /g allows us to do this in a single line of code. rather than short strings. Applying «^a» to “abc” matches „a”. I have explained literal characters and character classes. This makes sense because those applications are designed to work with entire files. «c$» matches „c” in “abc”. and “end of string” must be matched right after it. like “first line\nsecond line” (where \n indicates a line break). In text editors like EditPad Pro or GNU Emacs. Likewise. Start of String and End of String Anchors Thus far. because «\d+» matches the 4. it will accept the input even if the user entered “qsdf4ghjk”. «^\s+» matches leading whitespace and «\s+$» matches trailing whitespace. . the anchors match before and after newlines when you specify RegexOptions. In both cases. It is traditionally called "multi-line mode". like this: m/^regex$/m. they match a position before. all the regex engines discussed in this tutorial have the option to expand the meaning of both anchors. the caret and dollar always match at the start and end of each line. Useful Applications When using regular expressions in a programming language to validate user input.Multiline. as well as after each line break (between “\n” and “s”). “regex”. rather than the entire string. In Perl. it is good practice to trim leading and trailing whitespace. because the «b» cannot be matched right after the start of the string. the line break will also be stored in the variable. Using ^ and $ as Start of Line and End of Line Anchors If you have a string consisting of multiple lines. The caret «^» matches the position before the first character in the string. «$» will still match at the end of the string (after the last “e”).NET. «^b» will not match “abc” at all. RegexOptions. while «a$» does not match at all. using anchors is very important. you do this by adding an m after the regex code. and also before every line break (between “e” and “\n”). you have to explicitly activate this extended functionality. the entire string must consist of digits for «^\d+$» to be able to match. you could use $input =~ s/^\s+|\s+$//g.. Instead. See below for the inside view of the regex engine. Because “start of string” must be matched before the match of «\d+». Similarly. In . In Perl. putting one in a regex will cause the regex engine to try to match a single character.50 6.

it can result in a zero-length match. the engine does not try to match it with the character. Looking Inside the Regex Engine Let's see what happens when we try to match «^4$» to “749\n486\n4” (where \n represents a newline character) in multi-line mode.Multiline). even when you turn on “multiline mode”.51 Permanent Start of String and End of String Anchors «\A» only ever matches at the start of the string. rather than at the very end of the string. Reading a line from a file with the text “joe” results in the string “joe\n”. Since the previous token was zero-width. "> ". the regex engine starts at the first character: “7”. there is one exception. This is true in all regex flavors discussed in this tutorial.NET. «4» is a literal character. for example. Using «^\d*$» to test if the user entered a number (notice the use of the star instead of the plus). The Regex. the regex engine does not advance to the next character in the string. As usual. However. The first token in the regular expression is «^». and after each newline. Zero-Length Matches We saw that the anchors match at a position. then «\Z» and «$» will match at the position before that line break. «\Z» only ever matches at the end of the string. This “enhancement” was introduced by Perl. Likewise. «\z» matches after the line break. and is copied by many regex flavors. In Perl. so the regex «^» matches at the start of the quoted message. However. the match does include a starting position. There are no other permutations of the .NET and PCRE. In VB. would cause the script to accept an empty string as a valid input. it is common to prepend a “greater than” symbol and a space to each line of the quoted message. Since the match does not include any characters. This means that when a regex only consists of one or more anchors. and insert the replacement string (greater than symbol and a space). and the replacement string is inserted there. the resulting string will end with a line break. just like we want it.Replace method will remove the regex match from the string. When applied to this string. when reading a line from a file. «\A[a-z]+\z» does not match “joe\n”. this can be very useful or undesirable. rather than matching a character. The engine then advances to the next regex token: «4». «^» indeed matches the position before “7”. Depending on the situation. It remains at “7”. «\A» and «\Z» only match at the start and the end of the entire file. we can easily do this with Dim Quoted as String = Regex. See below. In email. We are using multi-line mode. Since this token is a zero-width token.Replace(Original. both «^[a-z]+$» and «\A[a-z]+\Z» will match „joe”. These two tokens never match at line breaks. RegexOptions. nothing is deleted. use «\z» (lower case z instead of upper case Z). including Java. where the caret and dollar always match at the start and end of lines. If you only want a match at the absolute very end of the string. Strings Ending with a Line Break Even though «\Z» and «$» only match at the end of the string (when the option for the caret and dollar to match at embedded line breaks is off). In EditPad Pro and PowerGREP. If the string ends with a line break. which does not match “7”. but rather with the position before the character that the regex engine has reached so far. which is not matched by the character class. matching only a position can be very useful. "^". .

Then. “9”. With success. The engine will proceed with the next regex token. The «^» can match at the position before the “4”. It matches the position before the void after the string. but does not advance the character position in the string. The engine continues at “9”. it was successfully matched at the second “4”. The next attempt. and the engine advances both the regex token and the string character. . It must be either a newline. What you have to watch out for is that String[Regex. No regex token that needs a character to match can match here. so it will try to match the position before the current character. The next token is «\d*». the dollar will check the current character. one of the star's effects is that it makes the «\d». Again. After that. Again. Not even a negated character class. Previously. Since «$» was the last token in the regex. but the star turns the failure of the «\d» into a zero-width success. Now the engine attempts to match «$» at the position before (indeed: before) the “8”. and that character is not a newline. As we will see later. in this case. At this point. and the mighty dollar is a strange beast. where the caret does not match. We already saw that those match. and fails again. Yet again. and the current character is advanced to the very last position in the string: the void after the string. because it is preceded by a newline character. because this position is preceded by a character. Let's see why. That fails. The current regex token is advanced to «$». This position is preceded by a character. or the void after the string. and that character is not a newline. at the next character: “4”.MatchPosition] may cause an access violation or segmentation fault. the dollar matches successfully. the entire regex has matched the empty string. This time. So the engine arrives at «$». because MatchPosition can point to the void after the string. the regex engine advances to the next regex token. Caution for Programmers A regular expression such as «$» all by itself can indeed match after the string. However. we are trying to match a dollar sign. It does not matter that this “character” is the void after the string. and the void after the string. It is zero-width. at “\n”. it would return zero. the engine has found a successful match: the last „4” in the string. «4». because it is preceded by the void before the string. There is only one “character” position in an empty string: the void after the string. optional. it would return the length of the string if string indices are zero-based.52 regex. without advancing the position in the string. If you would query the engine for the character position. so the engine continues at the next character. «4» matches „4”. The dollar cannot match here. If you would query the engine for the length of the match. the engine must try to match the first token again. In fact. also fails. The engine will try to match «\d» with the void after the string. so the engine starts again with the first regex token. Since that is the case after the example. «^» cannot match at the position before the 4. for «$» to match the position before the current character. The first token in the regex is «^». or the length+1 if string indices are one-based in your programming language. Same at the six and the newline. the regex engine arrives at the second “4” in the string. and that character is not a newline. Finally. This can also happen with «^» and «^$» if the last character in the string is a newline. “8”. the engine successfully matches «4» with „4”. and the engine reports success. Another Inside Look Earlier I mentioned that «^\d*$» would successfully match an empty string. the position before “\n” is preceded by a character. the regex engine tries to match the first token at the third “4” in the string.

Between a word character and a non-word character following right after the word character. «\b» cannot match at the position between the “T” and the “h”. Again. Between a non-word character and a word character following right after the non-word character. the position before the character is inspected. So «\b4\b» can be used to match a 4 that is not part of a larger number. if the first character is a word character. All characters that are not “word characters” are “non-word characters”. «i» does not match “T”. Looking Inside the Regex Engine Let's see what happens when we apply the regex «\bis\b» to the string “This island is beautiful”. . After the last character in the string. because the previous regex token was zero-width. The next character in the string is a space. and neither between the “i” and the “s”. «\B» matches at any position between two word characters as well as at any position between two non-word characters. the engine continues with the «i» which does not match with the space. Note that «\w» usually also matches digits. Simply put: «\b» allows you to perform a “whole words only” search using a regular expression in the form of «\bword\b». Effectively. So saying "«\b» matches before and after an alphanumeric sequence“ is more exact than saying ”before and after a word". «\b» matches here because the space is not a word character. there is only one metacharacter that matches both before a word and after a word. Word Boundaries The metacharacter «\b» is an anchor like the caret and the dollar sign. This regex will not match “44 sheets of a4”. This match is zero-length.53 7. A “word character” is a character that can be used to form words. It matches at a position that is called a “word boundary”. The engine continues with the next token: the literal «i». All non-word characters are always matched by «\W». Using only one operator makes things easier for you. Negated Word Boundary «\B» is the negated version of «\b». «\b» matches here. and the preceding character is. The engine starts with the first token «\b» at the first character “T”. «\B» matches at every position where «\b» does not. The engine does not advance to the next character in the string. if the last character is a word character. This is because any position between characters can never be both at the start and at the end of a word. but all word characters are always matched by the short-hand character class «\w». In Perl and the other regex flavors discussed in this tutorial. There are four different positions that qualify as word boundaries: • • • • Before the first character in the string. so the engine retries the first token at the next character position. It cannot match between the “h” and the “i” either. Since this token is zero-length. The exact list of characters is different for each regex flavor. because the T is a word character and the character before it is the void before the start of the string.

the regex engine finds that «i» matches „i” and «s» matches „s”. and the character before it is. The engine has successfully matched the word „is” in our string. it would have matched the „is” in “This”. «\b». also matches at the position before the second space in the string because the space is not a word character. . and finds that «i» matches „i” and «s» matches «s». Continuing. But «\b» matches at the position before the third “i” in the string. the «\b» fails to match and continues to do so until the second space is reached. Now. It matches there. the engine tries to match the second «\b» at the position before the “l”.54 Advancing a character and restarting with the first regex token. The engine reverts to the start of the regex and advances one character to the “s” in “island”. This fails because this position is between two word characters. skipping the two earlier occurrences of the characters i and s. If we had used the regular expression «is». but matching the «i» fails. «\b» matches between the space and the second “i” in the string. The engine continues. The last token in the regex. Again.

it considers the entire alternation to have been successfully matched as soon as one of the options has. or. So it knows that this regular expression uses alternation. The obvious solution is «Get|GetValue|Set|SetValue». «e» matches „e”. This tells the regex engine to find a word boundary. Set or SetValue. The match fails. The next token is the first «S» in the regex. We do not want to match Set or SetValue if the string is “SetValueFunction”. At this point.55 8. Alternation is similar. If you want more options. «SetValue» will be attempted before «Set». «t» matches „t”. the third option in the alternation has been successfully matched. “S”. If you want to search for the literal text «cat» or «dog». «G». the order of the alternatives matters. Suppose you want to use a regex to match a list of function names in a programming language: Get. The alternation operator has the lowest precedence of all regex operators. or everything to the right of the vertical bar. and change the order of the options. there are no other tokens in the regex outside the alternation. If we want to improve the first example to match whole words only. we would need to use «\b(cat|dog)\b». Because the regex engine is eager. If we had omitted the round brackets. The match fails again. so the entire regex has successfully matched „Set” in “SetValue”. and at the first character in the string. Alternation with The Vertical Bar or Pipe Symbol I already explained how you can use character classes to match a single character out of several possible characters. Contrary to what we intended. GetValue. One option is to take into account that the regex engine is eager. being the second «G» in the regex. and the engine continues with the next character in the string. Let's see how this works out when the string is “SetValue”. The regex engine starts at the first token in the regex. The match succeeds. If you want to limit the reach of the alternation. We could also combine the four options into two and use the question mark to make part of them optional: «Get(Value)?|Set(Value)?». we can optimize this further to «\b(Get|Set)(Value)?\b». If we use «GetValue|Get|SetValue|Set». the regex engine would have searched for “a word boundary followed by cat”. So it continues with the second option. you will need to use round brackets for grouping. it tells the regex engine to match either everything to the left of the vertical bar. You can use alternation to match a single regular expression out of several possible regular expressions. the regex did not match the entire string. Remember That The Regex Engine Is Eager I already explained that the regex engine is eager. The next token in the regex is the «e» after the «S» that just successfully matched. In this example. separate both options with a vertical bar or pipe symbol: «cat|dog». simply expand the list: «cat|dog|mouse|fish». The next token. then either “cat” or “dog”. It will stop searching as soon as it finds a valid match. . There are several solutions. and the engine will match the entire string. «SetValue» will be attempted before «Set». "dog followed by a word boundary. So the solution is «\b(Get|GetValue| Set|SetValue)\b» or «\b(Get(Value)?|Set(Value)?)\b». The consequence is that in certain situations. However. That is. The best option is probably to express the fact that we only want to match complete words. Since all options have the same end. as well as the next token in the regex. the regex engine studied the entire regular expression before starting. and then another word boundary. and that the entire regex has not failed yet. Because the question mark is greedy.

the question mark tells the regex engine that failing to match «u» is acceptable. . This fails.56 9. This fails. The first token in the regex is the literal «c». the engine starts again trying to match «c» to the first o in “colonel”.e.g. The engine continues.: «Nov(ember)?» will match „Nov” and „November”. «c» will match with the „c” in “color”. Then the engine checks whether «u» matches “n”. Therefore. The engine will always try to match that part. the engine will skip ahead to the next regex token: «r». You can write a regular expression that matches many alternatives by including more than one question mark. The question mark gives the regex engine two choices: try to match the part the question mark applies to. But this fails to match “n” as well. Again: no problem. „February 23”. «l» matches „l” and another «o» matches „o”. «l» and «o» match the following characters. 2003”. However.: «colou?r» matches both „colour” and „color”. E. This matches „r” and the engine reports that the regex successfully matched „color” in our string. After a series of failures. Looking Inside The Regex Engine Let's apply the regular expression «colou?r» to the string “The colonel likes the color green”. the engine can only conclude that the entire regular expression cannot be matched starting at the „c” in “colonel”. I have introduced the first metacharacter that is greedy. I will say a lot more about greediness when discussing the other repetition operators. «Feb(ruary)? 23(rd)?» matches „February 23rd”.g. You can make several tokens optional by grouping them together using round brackets. The first position where it matches successfully is the „c” in “colonel”. The effect is that if you apply the regex «Feb 23(rd)?» to the string “Today is Feb 23rd. Only if this causes the entire regular expression to fail. You can make the question mark lazy (i. or do not try to match it. Important Regex Concept: Greediness With the question mark. Therefore. Optional Items The question mark makes the preceding token in the regular expression optional. and finds that «o» matches „o”. Now the engine checks whether «u» matches “r”. and placing the question mark after the closing bracket. turn off the greediness) by putting a second question mark after the first. „Feb 23rd” and „Feb 23”. E. the match will always be „Feb 23rd” and not „Feb 23”. and «o». The question mark allows the engine to continue with «r». Now. will the engine try ignoring the part the question mark applies to.

Only if that causes the entire regex to fail. Limiting Repetition Modern regex flavors. After that. and proceed with the remainder of the regex. The asterisk or star tells the engine to attempt to match the preceding token zero or more times.4}\b» matches a number between 100 and 99999. That is.max}. You know that the input will be a valid HTML file. Like the plus. like those discussed in this tutorial. it's OK if the second character class matches nothing.}» is the same as «*». I could also have used «<[A-Za-z0-9]+>». You could use «\b[1-9][0-9]{3}\b» to match a number between 1000 and 9999. which is not a valid HTML tag. Obviously not what we wanted. matching „T”. and max is an integer equal to or greater than min indicating the maximum number of matches. I will present you with two possible solutions. The regex will match „<EM>first</EM>”. Most people new to regular expressions will attempt to use «<. I did not.57 10. The star repeats the second character class. So our regex will match a tag like „<B>”. The first character class matches a letter. When matching „<HTML>”. The second character class matches a letter or digit. the maximum number of matches is infinite. the first character class will match „H”. Repetition with Star and Plus I already introduced one repetition operator or quantifier: the question mark. because this regex would match „<1>”. «\b[1-9][09]{2. The sharp brackets are literals. Notice the use of the word boundaries. „M” and „L” with each step. and «{1. the plus causes the regex engine to repeat the preceding token as often as possible.}» is the same as «+». That is. make it give up the last iteration. If the comma is present but max is omitted. You might expect the regex to match „<EM>” and when continuing after that match. Omitting both the comma and max tells the engine to repeat the token exactly min times. But this regex may be sufficient if you know the string you are searching through does not contain any such invalid tags. . „</EM>”. in effect making it optional. But it does not. Because we used the star. it is an HTML tag. The syntax is {min. it will go back to the plus. The plus tells the engine to attempt to match the preceding token once or more. «<[A-Za-z][A-Za-z0-9]*>» matches an HTML tag without any attributes. So «{0. the star and the repetition using curly braces are greedy. where min is a positive integer number indicating the minimum number of matches. They will be surprised when they test it on a string like “This is a <EM>first</EM> test”.+>». The star will cause the second character class to be repeated three times. It tells the engine to attempt match the preceding token zero times or once. Let's take a look inside the regex engine to see in detail how this works and why this causes our regex to fail. have an additional repetition operator that allows you to specify how many times a token can be repeated. Watch Out for The Greediness! Suppose you want to use a regex to match an HTML tag. will the regex engine backtrack. so the regular expression does not need to exclude any invalid use of sharp brackets. If it sits between sharp brackets. The reason is that the plus is greedy.

The last token in the regex has been matched. But this time. Laziness Instead of Greediness The quick fix to this problem is to make the plus lazy instead of greedy.+» is reduced to „EM>first</EM”. «>» can match the next character in the string. the backtracking will force the lazy plus to expand rather than reduce its reach. The next token is the dot. (Remember that the plus requires the dot to match only once. The dot will match all remaining characters in the string. We can use a greedy plus and a negated character class: «<[^>]+>». and the engine tries again to continue with «>». The dot is repeated by the plus. Only at this point does the regex engine continue with the next token: «>». So the engine continues backtracking until the match of «. The total match so far is reduced to „<EM>first</EM> te”. Remember that the regex engine is eager to return a match. there is a better option than making the plus lazy. Again. The engine reports that „<EM>” has been successfully matched. This tells the regex engine to repeat the dot as few times as possible. That's more like it. The minimum is one. Now. The requirement has been met. and then continue trying the remainder of the regex. «>» cannot match here.58 Looking Inside The Regex Engine The first token in the regex is «<». the engine will backtrack. The dot fails when the engine has reached the void after the end of the string.+» is expanded to „EM”. the engine will backtrack. It will reduce the repetition of the plus by one. Now. The dot matches „E”. «<. the engine has to backtrack for each character in the HTML tag that it is trying to match. and the dot is repeated once more. As we already know.+?>». so the regex continues to try to match the dot with the next character. Because of greediness. Again. „>” is matched successfully. and the engine continues repeating the dot. the curly braces and the question mark itself. The reason why this is better is because of the backtracking. When using the negated character class. The plus is greedy. You can do the same with the star. which matches any character except newlines. The engine reports that „<EM>first</EM>” has been successfully matched. So our example becomes «<. «<» matches the first „<” in the string. no backtracking occurs at all when the string contains valid HTML code.) Rather than admitting failure. So the engine matches the dot with „E”. This fails. So the match of «. The next token is the dot. the first place where it will match is the first „<” in the string. The engine remembers that the plus has repeated the dot more often than is required.+» has matched „<EM>first</EM> test” and the engine has arrived at the end of the string. It will not continue backtracking further to see if there is another possible match. An Alternative to Laziness In this case.+» is reduced to „EM>first</EM> tes”. Therefore. and the engine continues with «>» and “M”. . the engine will repeat the dot as many times as it can. causing the engine to backtrack further. You should see the problem by now. The next character is the “>”. This is a literal. The dot matches the „>”. But «>» still cannot match. So the match of «. Let's have another look inside the regex engine. The next token in the regex is still «>». „M” is matched. When using the lazy plus. So far. these cannot match. this time repeated by a lazy plus. this is the leftmost longest match. You can do that by putting a question markbehind the plus in the regex. It will report the first valid match it finds. Again. But now the next character in the string is the last “t”. The last token in the regex has been matched.

. but they also do not support lazy repetition operators. They do not get the speed penalty. You will not notice the difference when doing a single search in a text editor. or perhaps in a custom syntax coloring scheme for EditPad Pro. But you will save plenty of CPU cycles when using such a regex is used repeatedly in a tight loop in a script that you are writing. Text-directed engines do not backtrack. remember that this tutorial only talks about regex-directed engines.59 Backtracking slows down the regex engine. Finally.

The question mark and the colon after the opening round bracket are the special syntax that you can use to tell the regex engine that this pair of brackets should not create a backreference. and “Pro version” in case „EditPad Pro” was matched. because it did not match anything. The regex «Set(Value)?» matches „Set” or „SetValue”. you can speed things up by using non-capturing parentheses. I have already used round brackets for this purpose in previous topics throughout this tutorial. . unless you use non-capturing parentheses. the first backreference will contain „Value”.60 11. slows down the regex engine because it has more work to do. to the entire group. depends on the tool you are using. you can optimize this regular expression into «Set(?:Value)?». A backreference stores the part of the string matched by the part of the regular expression inside the parentheses. This operator cannot appear after an opening round bracket. round brackets also create a “backreference”. \U1 inserts the first backreference in uppercase.g. a repetition operator. you can use the backreference in the replacement text during a search-and-replace operation by typing \1 (backslash one) into the replacement text. the actual replacement will be “Lite version” in case „EditPad Lite” was matched. e. \L1 in lowercase and \F1 with the first character in uppercase and the remainder in lowercase. How to Use Backreferences Backreferences allow you to reuse part of the regex match. In the second case. In EditPad Pro or PowerGREP. at the expense of making your regular expression slightly harder to read. If you do not use the backreference. Note that only round brackets can be used for grouping. or afterwards. Round Brackets Create a Backreference Besides grouping part of a regular expression together. and curly braces are used by a special repetition operator. Square brackets define a character class. What you can do with it afterwards. You can reuse it inside the regular expression (see below). \I1 inserts it with the first letter of each word capitalized. That is. Use Round Brackets for Grouping By placing part of a regular expression inside round brackets or parentheses. The colon indicates that the change we want to make is to turn off capturing the backreference. Finally. If you searched for «EditPad (Lite|Pro)» and use “\1 version” as the replacement. Remembering part of the regex match in a backreference. the first backreference will be empty. If you do not use the backreference. and the other letters in lowercase. you can group that part of the regular expression together. EditPad Pro and PowerGREP have a unique feature that allows you to change the case of the backreference. because an opening bracket by itself is not a valid regex token. In the first case. Therefore. Note the question mark after the opening bracket is unrelated to the question mark at the end of the regex. This allows you to apply a regex operator. That question mark is the regex operator that makes the previous token optional. there is no confusion between the question mark as an operator to make a token optional. and the question mark as a character to change the properties of a pair of round brackets.

This object has a property called Groups. Therefore.61 Regex libraries in programming languages also provide access to the backreference. to insert backreferences. The «/» before it is simply the forward slash in the closing HTML tag that we are trying to match. It will simply be replaced with nothingness. This regex contains only one pair of parentheses. In EditPad Pro or PowerGREP. because that would force the engine to continuously keep an extra copy of the entire regex match. In Perl. we can reuse the name of the tag for the closing tag. which capture the string matched by «[A-Z][A-Z0-9]» into the first backreference. In the replacement text. The Entire Regex Match As Backreference Zero Certain tools make the entire regex match available as backreference zero. etc. it will either give an error message. $2.*?</\1>». Suppose you want to match a pair of opening and closing HTML tags. etc. \0 cannot be used inside a regex. If a backreference was not used in a particular match attempt (such as in the first example where the question mark made the first backreference optional). the magic variable $& holds the entire regex match. Here's how: «<([A-Z][A-Z09]*)[^>]*>. etc.Groups[3]. The first bracket starts backreference number one. To figure out the number of a particular backreference. but also during the match. Non-capturing parentheses are not counted. scan the regular expression from left to right and count the opening round brackets. the item with index zero holds the entire regex match. . Using backreference zero is more efficient than putting an extra pair of round brackets around the entire regex. Using an empty backreference in the regex is perfectly fine. By putting the opening tag into a backreference. you can use $1. it is simply empty. you can use the entire regex match in the replacement text during a search and replace operation by typing \0 (backslash zero) into the replacement text. $2. Using Backreferences in The Regular Expression Backreferences can not only be used after a match has been found. you can use MyMatch. to access the part of the string matched by the backreference. In Perl. «([a-c])x\1x\1» will match „axaxa”. Depending on your regex flavor. In . «([abc]\1)» will not work. you can use the Match object that is returned by the Match method of the Regex class. you can use the magic variables $1.NET (dot net). Libraries like . the second number two.Value. This backreference is reused with «\1» (backslash one).NET (dot net) Regex class also has a method Replace that can do a regex-based search-and-replace on a string. and the text in between. You can reuse the same backreference more than once. This can be very useful when modifying a complex regular expression.NET (dot net) where backreferences are made available as an array or numbered list. „bxbxb” and „cxcxc”. The . To get the string matched by the third backreference in C#. A backreference cannot be used inside itself. only in the replacement. which is a collection of Group objects. or it will fail to match anything without an error message. This fact means that non-capturing parentheses have another benefit: you can insert them into a regular expression without changing the numbers assigned to the backreferences.

62 Looking Inside The Regex Engine Let's see how the regex engine applies the above regex to the string “Testing <B><I>bold italic</I></B> text”. In this case. Because of the laziness. These obviously match. so „b” remains. The next token is «[A-Z]». The second time „a” and the third time „b”. Backtracking continues again until the dot has consumed „<I>bold italic</I>”. because of the star. The star is still lazy. The backtracking continues until the dot has consumed „<I>bold italic”. so the engine backtracks again. The dot matches the second „<” in the string. it holds «b» which fails to match “c”. However. This also means that «([abc]+)=\1» will match „cab=cab”. That is because in the second regex. so the engine again backtracks. At this point. the previous value was overwritten. There is a clear difference between «([abc]+)» and «([abc])+». «<» matches „<” and «/» matches „/”. The regex engine also takes note that it is now inside the first pair of capturing parentheses. repeated by a lazy star. The regex engine will traverse the string until it can match at the first „<” in the string. This match fails. These match. The next token is «/». and position in the regex is advanced to «>». Again. «[^>]» does not match „>”. This does not match “I”. while the second regex will only store „b”. the previously saved match is overwritten. The first time. The first token in the regex is the literal «<». the first regex will put „cab” into the first backreference. and the next token is «/» which matches “/”. It will use the last match saved into the backreference each time it needs to be used. If a new match is found by capturing parentheses. «B» matches „B”. The last token in the regex. The next token is «\1». the plus caused the pair of parentheses to repeat three times. it will read the value that was stored. «[A-Z]» matches „B”. This prompts the regex engine to store what was matched inside them into the first backreference. „c” was stored. The engine arrives again at «\1». After storing the backreference. taking note that it should backtrack in case the remainder of the regex fails. the new value stored in the first backreference would be used. This step crosses the closing bracket of the first pair of capturing parentheses. At this point. These do not match. because of another star. that's perfectly fine. Obvious when you look at a . so the engine again takes note of the available backtracking position and advances to «<» and “I”. so „B” it is. the regex engine does not permanently substitute backreferences in the regular expression. and the dot consumes the third “<” in the string. The position in the regex is advanced to «[^>]». and not «B». The engine has now arrived at the second «<» in the regex. Note that the token the backreference. This means that if the engine had backtracked beyond the first pair of capturing parentheses before arriving the second time at «\1». Repetition and Backreferences As I mentioned in the above inside look. the regex engine will initially skip this token. the engine proceeds with the match attempt. and that «([abc])+=\1» will not. The position in the string remains at “>”. The backreference still holds „B”. «>» matches „>”. The engine advances to «[A-Z0-9]» and “>”. «<» matches the third „<” in the string. Though both successfully match „cab”. and the engine is forced to backtrack to the dot. The reason is that when the engine arrives at «\1». Every time the engine arrives at the backreference. The position in the string remains at “>”. Each time. and the second “<” in the string. The engine does not substitute the backreference in the regular expression. But this did not happen here. The next token is a dot. this is not a problem. This fails to match at “I”. „B” is stored. A complete match has been found: „<B><I>bold italic</I></B>”.

simply type in “\1” as the replacement text and click the Replace button. at least not as metacharacters. When using backreferences. So the regex «[(a)b]» matches „a”. Parentheses and Backreferences Cannot Be Used Inside Character Classes Round brackets cannot be used inside character classes. doubled words such as “the the” easily creep in. Using the regex «\b(\w+)\s+\1\b» in your text editor. „(” and „)”. When you put a round bracket in a character class. always double check that you are really capturing what you want. but a common cause of difficulty with regular expressions nonetheless. To delete the second word. you can easily find them. So this regex will match an a followed by either «\x01» or a «b».63 simple example like this one. The \1 in regex like «(a)[\1b]» will be interpreted as an octal escape in most regex flavors. Backreferences also cannot be used inside a character class. it is treated as a literal character. . Useful Example: Checking for Doubled Words When editing text. „b”.

NET languages. you can reference the named group with the familiar dollar sign syntax: “${name}”. where the sharp brackets are used for HTML tags. Use Round Brackets for Grouping All modern regular expression engines support capturing groups. where single quotes may need to be escaped.Text.64 12. Here is an example with two capturing groups in . and will convert one flavor of named capture into the other when generating source code snippets for Python. As you can see. and number both kinds from left to right. the numbering can get a little confusing. RegexBuddy supports both Python's and Microsoft's style. In PHP. When doing a search-and-replace. The PHP preg functions offer the same functionality. The second syntax is preferable in ASP code. Again. PCRE and PHP Python's regex module was the first to offer a solution: named capture. . By assigning a name to a capturing group. no other regex flavor supports Microsoft's version of named capture. You can use the pointy bracket flavor and the quoted flavors interchangeably. and offers named capture using the same syntax. Python's sub() function allows you to reference a named group as “\1” or “\g<name>”. the Microsoft developers decided to invent their own syntax. Python and PCRE treat named capturing groups just like unnamed capturing groups.NET framework also support named capture. PHP/preg. since they are based on PCRE. or to use part of the regex match for further processing. The open source PCRE library has followed Python's example. The numbers can then be used in backreferences to match the same text again in the regular expression. In a complex regular expression with many capturing groups. Simply use a name instead of a number between the curly braces.NET offers two syntaxes to create a capturing group: one using sharp brackets. Named Capture with .RegularExpressions The regular expression classes of the . rather than follow the one pioneered by Python. PHP. starting with one. starting with one. Named Capture with Python. use «\k<name>» or «\k'name'». or one of the . and the other using single quotes. To reference a capturing group inside the regex. you can use the two syntactic variations interchangeably. which are numbered from left to right. You can reference the contents of the group with the numbered backreference «\1» or the named backreference «(?P=name)». The regex . Currently. «(?P<name>group)» captures the match of «group» into the backreference “name”. The first syntax is preferable in strings. you can use double-quoted string interpolation with the $regs parameter you passed to pcre_match(): “$regs['name']”. Unfortunately.NET style: «(?<first>group)(?'second'group)». Names and Numbers for Capturing Groups Here is where things get a bit ugly. you can easily reference it by name.NET's System. This does not work in PHP.

. If you do a search-and-replace with this regex and the replacement “\1\2\3\4”. or make it non-capturing as in «(?:nocapture)». you will get “acbd”. Non-capturing groups are more efficient. from one till four. when using . So the unnamed groups «(a)» and «(c)» get numbered first.NET framework does number named capturing groups from left to right. Probably not what you expected.NET framework.NET's regex support. All four groups were numbered from left to right. Either give a group a name. in this case: three. Things are quite a bit more complicated with the . To keep things compatible across regex flavors. To make things simple. The . just assume that named groups do not get numbered at all. since the regex engine does not need to keep track of their matches. you will get “abcd”. Easy and logical. from left to right. I strongly recommend that you do not mix named and unnamed capturing groups at all. continuing from the unnamed groups. The regex «(a)(?<x>b)(c)(?<y>d)» again matches „abcd”. starting at one.65 «(a)(?P<x>b)(c)(?P<y>d)» matches „abcd” as expected. if you do a search-and-replace with “$1$2$3$4” as the replacement. and reference them by name exclusively. Then the named groups «(?<x>b)» and «(?<y>d)» get their numbers. However. but numbers them after all the unnamed groups have been numbered.

You can turn off a mode by preceding it with a minus sign. It is obvious that the modifier span does not create a backreference.g. Regex Matching Modes All regular expression engines discussed in this tutorial support the following three matching modes: • • • /i makes the regex match case insensitive. You can quickly test this.g. If you insert the modifier (?ism) in the middle of the regex. To turn off several modes. /m enables "multi-line mode". the non-capturing group is a modifier span that does not change any modifiers. precede each of their letters with a minus sign. E. (?i) turns on case insensitivity. the tool or language does not provide the ability to specify matching options. Specifying Modes Inside The Regular Expression Sometimes. the handy String.CASE_INSENSITIVE) does the same in Java. In that situation.g. Turning Modes On and Off for Only Part of The Regular Expression Modern regex flavors allow you to apply modifiers to only part of the regular expression. In this mode. one to turn an option on. turns off single-line mode. m/regex/i turns on case insensitivity. while Pattern. Technically.compile(“regex”. E. Pattern. the caret and dollar match before and after newlines in the subject string. In this mode.g. (?i-sm) turns on case insensitivity. in Perl. /s enables "single-line mode". the dot matches newlines. Older regex flavors usually apply the option to the entire regular expression. Most programming languages allow you to pass option flags when constructing the regex object. no matter where you placed it.matches() method in Java does not take a parameter for matching options like Pattern. while (?ism) turns on all three options. but not “teST” or “TEST”.66 13. and turns on multi-line mode. Many regex flavors have additional modes or options that have single letter equivalents. . you use a modifier span. Modifier Spans Instead of using two modifiers. «(?i)ignorecase(?-i)casesensitive(?i)ignorecase» is equivalent to «(?i)ignorecase(?i:casesensitive)ignorecase». the modifier only applies to the part of the regex to the right of the modifier. Not all regex flavors support this. The regex «(?i)te(?-i)st» should match „test” and „TEst”. Most tools that support regular expressions have checkboxes or similar controls that you can use to turn these modes on or off. E. E. You have probably noticed the resemblance between the modifier span and the non-capturing group «(?:group)». you can add a mode modifier to the start of the regex. and one to turn it off.compile() does. but these differ widely. The latest versions of all tools and languages discussed in this book do.

Since there is still no P.10. it stopped responding) when trying to find lines in a comma-delimited text file where the 12th item on a line started with a “P”. and 11th iterations.» has consumed „11.12. Because of the double repetition (star inside {11}). and gradually expand the match as the engine backtracks through the regex to find an overall match.67 14. Finally. A lazy quantifier will first repeat the token as few times as required.11.10. there are more possiblities to be tried.11. this regex looks like it should do the job just fine. But it does not give up there. I explained the difference between greedy and lazy repetition.2. At that point.8. Because greediness and laziness change the order in which permutations are tried.4. „9. This causes software like EditPad Pro to stop responding. let's see why backtracking can lead to problems.3.12. so the dot continues until the 11th iteration of «.10.11. this leads to a catastrophic amount of backtracking. It will backtrack to the point where «^(. they can change the overall regex match.*?.){11}» had consumed „1.». The problem rears its ugly head when the 12th field does not start with a P.4. The lazy dot and comma match a single comma-delimited field.7. The next token is again the dot. Atomic Grouping and Possessive Quantifiers When discussing the repetition operators or quantifiers. subsequently expanding it to „9. Catastrophic Backtracking Recently I got a complaint from a customer that EditPad Pro hung (i.”.”. The dot matches a comma. the 10th could match just „11. A greedy quantifier will first try to repeat the token as many times as possible.7. The dot matches the comma! However. giving up the last match of the comma. However.*?.13”. The customer was using the regexp «^(.e.11”. the regex engine will backtrack. In fact. the regex engine can no longer match the 11th iteration of «. . they do not change the fact that the regex engine will backtrack to try all possible permutations of the regular expression in case no match can be found.10. and gradually give up matches as the engine backtracks to find an overall match.5. or even crash as the regex engine runs out of memory trying to remember all backtracking positions.9.11.”.5. Reaching the end of the string again. You get the idea: the possible number of combinations that the regex engine will try for each line where the 12th field does not start with a P is huge. this is exactly what will happen when the 12th field indeed starts with a P. and the {11} skips the first 11 fields.10. It does not.” as well as „11. the comma does not match the “1” in the 12th field.){11}P». At first sight. But between each expansion.11. Since there is no comma after the 13th field. „9.6. expanding the match of the 10th iteration to „10. 10th. again trying all possible combinations for the 9th. Continuously failing.3.12. the P checks if the 12th field indeed starts with P.2. First.”. It backtracks to the 10th iteration.12.12.9. When the 9th iteration consumes „9.6. The regex engine now checks whether the 13th field starts with a P.*?.”. Let's say the string is “1. the same story starts with the 9th iteration. the 10th iteration is expanded to „10. the engine backtracks to the 8th iteration. You can already see the root of the problem: the part of the regex (the dot) matching the contents of the field also matches the delimiter (the comma).”.10.8.”.”. Greediness and laziness determine the order in which the regex engine tries the possible permutations of the regex pattern.*?.

2. But that is not always possible in such a straightforward manner. and only supported by the latest versions of most regex flavors. Possessive quantifiers are a limited form of atomic grouping with a cleaner notation. though the JDK documentation uses the term “independent group” rather than “atomic group”.6. It would match the minimum number of matches and never expand the match because backtracking is not allowed. So the regex becomes: «^([^.4. The fields must not contain comma's. If backtracking is required.\r\n]» is not able to expand beyond the comma. In that case. and each time the «[^. . Note that you cannot make a lazy quantifier possessive. We want to match 11 commadelimited fields. you can use «x*+». possessive quantifiers are only supported by the Java JDK 1. In the above example.){11})P». Their purpose is to prevent backtracking. as do all versions of RegexBuddy. as do recent versions of PCRE and PHP's pgreg functions. «x++» is the same as «(?>x+)». If the P cannot be found. no backtracking can take place once the regex engine has found a match for the group. If there is no token before the group.4. Similarly. If repeating the inner loop 4 times and the outer loop 7 times results in the same overall match as repeating the inner loop 6 times and the outer loop 2 times.0 and later. the solution is to be more exact about what we want to match. But it will backtrack only 11 times. place a plus after it.\r\n]*.NET support atomic grouping. you should use atomic grouping to prevent the regex engine from backtracking. The Java supports it starting with JDK version 1. Everything between (?>) is treated as one single token by the regex engine. the engine will still backtrack. In our example. At this time. the above regex becomes «^(?>(. Python does not support atomic grouping. Using atomic grouping. Perl supports it starting with version 5. Because the entire group is one token. Tool and Language Support for Atomic Grouping and Possessive Quantifiers Atomic grouping is a recent addition to the regex scene.){11}P». without trying further options. make absolutely sure that there is only one way to match the same match.68 Preventing Catastrophic Backtracking The solution is simple. All versions of . forcing the regex engine to the previous one of the 11 iterations immediately. To make a quantifier possessive. and PCRE version 4 and later. When nesting repetition operators.n}+». Atomic Grouping and Possessive Quantifiers Recent regex flavors have introduced two additional solutions to this problem: atomic grouping and possessive quantifiers. once the regex engine leaves the group. The latest versions of EditPad Pro and PowerGREP support both atomic grouping and possessive quantifiers. you can be sure that the regex engine will try all those combinations. allowing the regex engine to fail faster. «x?+» and «x{m. the regex must retry the entire regex at the next position in the string. we could easily reduce the amount of backtracking to a very low level by better specifying what we wanted. the engine has to backtrack to the regex token before the group (the caret in our example).*?.

«P» failed to match. With the former regex. The engine now tries to match the caret at the next position in the string.8. and the comma matches too. using simple repetition. often it is not. you can reduce clutter by writing «^(?>([^. so the engine backtracks.*?. the engine leaves the atomic group.12. «\d+6» will match „123456” in “123456789”. That is. The previous token is an atomic group. Failure is declared after 30 attempts to match the caret. But the comma does not match “1”. With simple repetition. and the match fails. Note that atomic grouping and possessive quantifiers can alter the outcome of the regular expression match. If you are simply doing a search in a text editor. With combined repetition. then atomic grouping may make a difference. If the final x in the regex cannot be matched. everything happened just like in the original. troublesome regular expression. They do not speed up success. The star is not possessive.\r\n]*+. «\d+» will match the entire string. The star is lazy.){11})P» is applied to “1.7. you often can avoid the problem without atomic grouping as in the example above.3.6. «{11}» causes further repetition until the atomic group has matched „1. That is what atomic grouping and possessive quantifiers are for: efficiency by disallowing backtracking. since possessive. no backtracking is allowed. you will not earn back the extra time to type in the characters for the atomic grouping. the regex engine backtracks once for each character matched by the star. which fails. «\d++6» will not match at all. If possessive quantifiers are available. Now.”. all backtracking information is discarded and the group is now considered a single token. That's right: backtracking is allowed here.5. Again. In the latter case. the regex engine did not cross the closing round bracket of the atomic group. rather than after 30 attempts to match the caret and a huge number of attempts to try all combinations of both quantifiers in the regex. the amount of time wasted with pointless backtracking increases in a linear fashion to the length of the string. so the engine backtracks to the dot. the engine backtracks until the 6 can be matched.9.69 Atomic Grouping Inside The Regex Engine Let's see how «^(?>(. and is not immediately enclosed by an atomic group. you really should use atomic grouping and/or possessive quantifiers whenever possible.2. the increase in speed is minimal.9. only failure. If the regex will be used in a tight loop in an application.\r\n]*).11. This fails. Sometimes this is desirable. Still.11. The dot matches „1”.13”. if you are smart about combined repetition. The caret matches at the start of the string and the engine enters the atomic group. Now comes the difference.7. and declares failure. and just one attempt to match the atomic group. greedy repetition of the star is faster than a backtracking lazy dot.){11})P».8. So far. or process huge amounts of data. When nesting quantifiers like in the above example.){11})P».2. the amount of time wasted increases exponentially and will very quickly exhaust the capabilities of your computer. This shows again that understanding how the regex engine works on the inside will enable you to avoid many pitfalls and craft efficient regular expressions that match exactly what you want. The engine now tries to match «P» to the “1” in the 12th field.6. The engine walks through the string until the end.10. so the dot is initially skipped. Because the group is atomic. While «x[^x]*+x» and «x(?>[^x]*)x» fail faster than «x[^x]*x».4. . When To Use Atomic Grouping or Possessive Quantifiers Atomic grouping and possessive quantifiers speed up failure by eliminating backtracking. the cause of this is that the token «\d» that is repeated can also match the delimiter «6». so the group's entire match is discarded and the engine backtracks further to the caret. The most efficient regex for our problem at hand would be «^(?>((?>[^.

which supports lookahead but not lookbehind. and discards the regex match. but then give up the match and only return the result: match or no match. you have to put capturing parentheses around the regex inside the lookahead. and start and end of word anchors that I already explained. They are zero-width just like the start and end of line. and „q” is returned as the match. Lookahead and Lookbehind Zero-Width Assertions Perl 5 introduced two very powerful constructs: “lookahead” and “lookbehind”. or that would get very longwinded without them. If it contains capturing parentheses. If you want to store the match of the regex inside a backreference. we have the trivial regex «u». Negative lookahead provides the solution: «q(?!u)». The exception is JavaScript. The negative lookahead construct is the pair of round brackets. «q(?=u)» matches a q that is followed by a u. The next token is the «u» inside the lookahead. The engine advances to the next character: “i”. Because the lookahead is negative. I will explain why below. However. but only assert whether a match is possible or not. these are called “lookaround”. So it is not included in the count towards numbering the backreferences. They do not consume characters in the string.70 15. the entire regex has matched. Note that the lookahead itself does not create a backreference. The difference is that lookarounds will actually match characters. with the opening bracket followed by a question mark and an equals sign. with the opening bracket followed by a question mark and an explanation point. The position in the string is now the void behind the string. Inside the lookahead. Regex Engine Internals First. it is done with the regex inside the lookahead. All regex flavors discussed in this book support lookaround. this will cause the engine to traverse the string until the „q” in the string is matched. Let's try applying the same regex to “quit”. the backreferences will be saved. like this: «(?=(regex))». This does not match the void behind the string. without making the u part of the match. this means that the lookahead has successfully matched at the current position. «q» matches „q”. (Note that this is not the case with lookbehind. When explaining character classes. let's see how the engine applies «q(?!u)» to the string “Iraq”. This causes the engine to step back in the string to “u”. . The first token in the regex is the literal «q». You can use any regular expression inside the lookahead. Positive and Negative Lookahead Negative lookahead is indispensable if you want to match something not followed by something else. They are also called “zero-width assertions”. The next character is the “u”. The engine notes success. The other way around will not work. The positive lookahead construct is a pair of round brackets. The next token is the lookahead. The engine takes note that it is inside a lookahead construct now. because the lookahead will already have discarded the regex match by the time the backreference is to be saved. At this point. Positive lookahead works just the same. As we already know. That is why they are called “assertions”. So the next token is «u».) Any valid regular expression can be used inside the lookahead. I already explained why you cannot use a negated character class to match a “q” not followed by a “u”. These match. Collectively. and begins matching the regex inside the lookahead. Lookarounds allow you to create regular expressions that are impossible to create without them. The engine notes that the regex inside the lookahead failed.

«(?<=a)b» (positive lookbehind) matches the „b” (and only the „b”) in „cab”. the lookbehind tells the engine to step back one character. the engine has to start again at the beginning. The next token is «b». So this match attempt fails. Let's apply «q(?=u)i» to “quit”. and notices that the „a” can be matched there. So the lookbehind fails. but will match the „b” (and only the „b”) in “bed” or “debt”. the engine reports failure. the match from the lookahead must be discarded. Important Notes About Lookbehind The good news is that you can use lookbehind anywhere in the regex. “less than” symbol and an equals sign. so the positive lookbehind fails again. It matches one character: the first „b” in the string. The engine steps back and finds out that „a” satisfies the lookbehind. The next character is the second “a” in the string. and the engine starts again at the next character. To lookahead was successful. to make sure you understand the implications of the lookahead. The engine starts with the lookbehind and the first character in the string. to check if the text inside the lookbehind can be matched there. which cannot match here. This is definitely not the same as . and finds out that the “m” does not match «a». the successful match inside it causes the lookahead to fail. Again. using an exclamation point instead of an equals sign. Let's take one more look inside. It tells the regex engine to temporarily step backwards in the string. More Regex Engine Internals Let's apply «(?<=a)b» to “thingamabob”. the current position in the string remains at the “m”. Positive and Negative Lookbehind Lookbehind has the same effect. All remaining attempts will fail as well. the “h”. and put a token after it. but works backwards. with the opening bracket followed by a question mark. but does not match “bed” or “debt”. The lookbehind continues to fail until the regex reaches the “m” in the string. The construct for positive lookbehind is «(?<=text)»: a pair of round brackets. The next character is the first “b” in the string. I have made the lookahead positive. and the entire regex has been matched successfully. «(?<!a)b» matches a “b” that is not preceded by an “a”.) Again. It will not match “cab”. The engine cannot step back one character because there are no characters before the “t”.71 Because the lookahead is negative. not only at the start. so the engine steps back from “i” in the string to “u”. and see if an “a” can be matched there. In this case. so the engine continues with «i». The engine steps back. Since there are no other permutations of this regex. «b» matches „b”. The engine again steps back one character. the engine temporarily steps back one character to check if an “a” can be found there. If you want to find a word not ending with an “s”. Since «q» cannot match anywhere else. «q» matches „q” and «u» matches „u”. (Note that a negative lookbehind would have succeeded here. using negative lookbehind. because there are no more q's in the string. you could use «\b\w+(?<!s)\b». The positive lookbehind matches. Negative lookbehind is written as «(?<!text)». Because it is zero-width. But «i» cannot match “u”. It finds a “t”. Again.

The reason is that regular expressions do not work backwards. Until that happens. Even with these limitations. Finally. Microsoft has promised to resolve this in version 2. but fixed lengths. These regex flavors recognize the fact that finite repetition can be rewritten as an alternation of strings with different. Some regex flavors support the above. I recommend you use only fixed-length strings. EditPad Pro and PowerGREP. but only if all options in the alternation have the same length. Not to regex engines. the semantics of applying a regular expression backwards are currently not well-defined. though. You can use any regex of which the length of the match can be predetermined. including those used by Perl 5 and Python. and will allow you to use any regex. Finally. The latter will also not match single-letter words like “a” or “I”. The string must be traversed from left to right. This includes PCRE.0 of the . The bad news is that you cannot use just any regex inside a lookbehind. This means you can use literal text and character classes. inside lookbehind. Therefore. Personally. the former will match „John” and the latter „John'” (including the apostrophe). some more advanced flavors support the above. Double negations tend to be confusing to humans. alternation and character classes inside lookbehind. You can use alternation. the regular expression engine needs to be able to figure out how many steps to step back before checking the lookbehind. plus alternation with strings of different lengths. The last regex. You cannot use repetition or optional items. and \W in the character class).4. Therefore. However. but you can use the question mark and the curly braces with the max parameter specified. The correct regex without using lookbehind is «\b\w*[^s\W]\b» (star instead of plus.NET framework. has a double negation (the \W in the negated character class). which works correctly. But each string in the alternation must still be of fixed length. so only literals and character classes can be used. the . lookbehind is a valuable addition to the regular expression syntax. RegexBuddy. When applied to “John's”. I find the lookbehind easier to understand. only allow fixed-length strings. plus finite repetition. many regex flavors. I will leave it up to you to figure out why. Technically. including infinite repetition. . PHP.NET framework can apply regular expressions backwards. (Hint: «\b» matches between the apostrophe and the “s”). This means you can still not use the star or plus. The only regex flavor that I know of that currently supports this is Sun's regex package in the JDK 1.72 «\b\w+[^s]\b». JavaScript does not support lookbehind at all.

it is often underused by people new to regular expressions. To make this clear. Unfortunately. Lookaround to The Rescue In this example. is a very powerful concept. If «cat» cannot be matched. we basically have two requirements for a successful match. where the lookahead will fail. the second «\w*» will consume the remaining letters. The engine will then backtrack. matches only when the current character position in the string is at the start of a 6-letter word in the string. Second. If «cat» can be successfully matched. So when the regex inside the lookahead has found the 6-letter word. If not. The confusing part is that the lookaround is zero-width. in the 6letter word. the lookahead will fail. Matching a 6-letter word is easy with «\b\w{6}\b». we know that «\b» matches and that the first «\w*» will match 6 times. Actually. We just specify all the options and hump them together using alternation: «cat\w{3}|\wcat\w{2}|\w{2}cat\w|\w{3}cat». the engine will first attempt the regex inside the positive lookahead. I would like to give you another. This is at the second letter in the 6-letter word we just found. Combining the two. Let's say we want to find a word that is six letters long and contains the three subsequent letters “cat”. we can match this without lookaround. the current position in the string is still at the beginning of the 6-letter word. Matching a word containing “cat” is equally easy: «\b\w*cat\w*\b». This sub-regex. But this method gets unwieldy if you want to find any word between 6 and 12 letters long containing either “cat”. a bit more practical example. causing the engine to advance character by character until the next 6-letter word. reducing the number of characters matched by «\w*». Easy enough. because lookaround is a bit confusing. “dog” or “mouse”. Because we already know that a 6-letter word can be matched at the current position. At this position will the regex engine attempt the remainder of the regex. and therefore the lookahead. . at the next character position in the string. Our double-requirement-regex has matched successfully. Testing The Same Part of The String for More Than One Requirement Lookaround. Easy! Here's how this works. if any. we want a word that is 6 letters long. which I introduced in detail in the previous topic. So if you have a regex in which a lookahead is followed by another piece of regex. the word we found must contain the word “cat”. the last «\b» in the regex is guaranteed to match where the second «\b» inside the lookahead matched. First. At each character position in the string where the regex is attempted. or a lookbehind is preceded by another piece of regex. After that. the engine has no other choice but to restart at the beginning of the regex. we get: «(?=\b\w{6}\b)\b\w*cat\w*\b». until «cat» can be matched.73 16. then the regex will traverse part of the string twice. and the engine will continue trying the regex from the start at the next character position in the string. The lookahead is zero-width.

If we omitted the «\w*». So we can optimize this to «\w{0. it is not the most optimal solution. optimization involves the first «\b». Remember that the lookahead discards its match. and therefore does not change the result returned by the regex engine. “dog” or “mouse”? Again we have two requirements. but if a 6-letter word does not contain “cat”. we cannot remove it because it adds characters to the regex match.9}(cat|dog|mouse)\w*».74 Optimizing Our Solution While the above regex works just fine. so it does not contribute to the match returned by the regex engine. One last. and even at one character beyond the 6-letter word. This regex will also put “cat”.3}». leaving: «(?=\b\w{6}\b)\w*cat\w*». there's no need to put it inside the lookahead.12}\b)\w{0. This is not a problem if you are just doing a search in a text editor. up to and including “cat”. But optimizing things is a good idea if this regex will be used repeatedly and/or on large chunks of data in an application you are developing. what would you use to find any word between 6 and 12 letters long containing either “cat”. Since it is zero-width itself. As it stands. which we can easily combine using a lookahead: « \b(?=\w{6. Though the last «\w*» is also guaranteed to match. The lazy asterisk would find a successful match sooner. there can never be more than 3 letters before “cat”.3}cat\w*». “dog” or “mouse” into the first backreference. You can discover these optimizations by yourself if you carefully examine the regex and follow how the regex engine applies it. So the final regex is: «\b(?=\w{6}\b)\w{0. we can remove them. . But we can optimize the first «\w*». But we know that in a successful match. Since it is zero-width. at the last single letter. So we have «(?=\b\w{6}\b)\w{0. I said the third and last «\b» are guaranteed to match. instead of the entire word. A More Complex Problem So. it will match 6 letters and then backtrack. it would still cause the regex engine to try matching “cat” at the last two letters. as I did above.3}cat\w*». Very easy. once you get the hang of it. minor. Note that making the asterisk lazy would not have optimized this sufficiently. the resulting match would be the start of a 6-letter word containing “cat”.

So we need a way to match „wanted” without matching the rest of the section. you can easily build a regex to do a search and replace on HTML files. Since we do not know in advance how many characters there will be between “start” and “wanted”. Effectively. This. replacing a certain word with another. not after „wanted”. When we apply the regex again to the same string or file. «start» and «stop» with the regexes of your choice. but only inside title tags. «start. So inside the lookahead we need to look for a series of unspecified characters that do not match the start of a section anywhere in the series. The star is obviously not of fixed length. If not. we need to use «. This is possible with lookahead. we found a match after a section rather than inside a section. However. at which point stop cannot be matched and thus the regex will fail. One example is matching a particular regex only inside specific sections of the string or file searched through. it will continue after „stop”. You may be tempted to use a combination of lookbehind and lookahead like in «(?<=start. How do we know if we matched «wanted» inside a section? First. A title tag starts with «<H[1-6]» and . Because of the negative lookahead inside the star. this will not work. this will not work if “wanted” occurs more than once inside a single section. To keep things simple.)*?stop)».*?stop)».*?)wanted(?=. we found a match before a section rather than inside a section. and «start» as the regex matching the start of the section. the star will also stop at the start of a section. If we could. and «stop» as the regex matching the end of the section. In a regex.*?wanted. The final regular expression becomes: «wanted(?=((?!start). I will use «wanted» as a substitute for the regular expression that we are trying to match inside the section. Note that these two rules will only yield success if the string or file searched through is properly translated into sections.)*?stop». The final regular expression will be in the form of «wanted(?=insidesection)». we can do without lookahead.*?». If “wanted” occurs only once inside the section. First we match the string we want. the lazy star will continue to repeat until the end of the section is reached. we need to match the end of the section. Example: Search and Replace within Header Tags Using the above generic regular expression. Second.75 17. Finding Matches Only Inside a Section of The String Lookahead allows you to create regular expression patterns that are impossible to create without it. because lookahead is zero-width. this is written as: «((?!start). The regex engine will refuse to compile this regular expression. The entire section is included in the regex match. That is. we repeat zero or more times with the star. I used a lazy star to make the regex more efficient. The dot and negative lookahead match any character that is not the first character of the start of a section. we must not be able to match «start» between matching «wanted» and matching «stop». After this. and then we test if it is inside the proper section. we must be able to match «stop» after matching «wanted». and end with the section stop.*?stop» would do the trick. The reason is that this regular expression consumes the entire section. So we have to resort to using lookahead only. Substitute «wanted». However. Lookbehind must be of fixed length. each match of «start» must be followed exactly by one match of «stop».

.76 ends with «</H[1-6]>». You may have noticed that I escaped the < of the opening tag in the final regex. or negative lookbehind. I did that because some regex flavors interpret «(?!<» as identical to «(?<!». So the regex becomes «wanted(?=((?!\<H[1-6]). I omitted the closing > in the start tag to allow for attributes.)*?</H[1-6]>)». Escaping the < takes care of the problem. But lookahead is what we need here.

During the fifth attempt. The 3rd attempt yields „s” and the 4th attempt matches the second „t” in the string. specify the continuation modifier /c. EditPad Pro will select the match. All this is very useful to make several regular expressions work together. End of The Previous Match vs Start of The Match Attempt With some regex flavors or tools.77 18. The fifth attempt fails.etc. Continuing at The End of The Previous Match The anchor «\G» matches at the position where the previous match ended. Applying it again matches „e”. This way you can parse the tags in the file in the order they appear in the file. and the regexes inside the loop check which tag we found.. When a match is found.g. The regex in the while loop searches for the tag's opening bracket. \G Magic with Perl In Perl. this makes a lot of sense in the context of a text editor. the position where the last match ended is a “magical” value that is remembered separately for each string variable. The position is not associated with any regular expression. rather than at the end of the previous match result. where «\G» matches at the position of the text cursor. But that position is not followed by a word character. so the match fails.. Applying «\G\w» to the string “test string” matches „t”. rather than the end of the previous match. During the first match attempt. To avoid this. . «\G» matches at the start of the string in the way «\A» does.. the stored position for «\G» is reset to the start of the string. The result is that «\G» matches at the end of the previous match result only when you do not move the text cursor between two searches. This is the case with EditPad Pro.. E. the only place in the string where «\G» matches is after the second t. If a match attempt fails. All in all. and move the text cursor to the end of the match. «\G» matches at the start of the match attempt. without having to write a single big regex that matches all tags you are interested in. you could parse an HTML file in the following fashion: while ($string =~ m/</g) { if ($string =~ m/\GB>/c) { } elsif ($string =~ m/\GI>/c) { } else { } } # Bold # Italics # . This means that you can use «\G» to make a regex continue in a subject string where another regex left off.

What you can do though is to add a line of code to make the match attempt of the second Matcher start where the match of the first Matcher ended. The Matcher is strictly associated with a single regular expression and a single subject string. in Java. . the position for «\G» is remembered by the Matcher object. E.78 \G in Other Programming Langauges This flexibility is not available with most other programming languages. «\G» will then match at this position.g.

then the regex engine will attempt to match the then or else part (depending on the outcome of the lookahead) at the same position where the if was attempted. This part can be followed by a vertical bar and the else part. Otherwise. If-Then-Else Conditionals in Regular Expressions A special construct «(?ifthen|else)» allows you to create conditional regular expressions. For the if part. like in «(?(?=condition)(then1|then2|then3)|(else1|else2|else3))». Otherwise. If you want to use alternation. there is no need to use parentheses around the then and else parts. the if and then parts are clearly separated. immediately followed by the then part. The opening bracket must be followed by a question mark. Remember that the lookaround constructs do not consume any characters.79 19. If you use a lookahead as the if part. you can use any regular expression. the else part is attempted instead. You may omit the else part. The syntax consists of a pair of round brackets. If the if part evaluates to true. you will have to group the then or else together using parentheses. the syntax becomes «(?(?=regex)then|else)». Using positive lookahead. For the then and else. and the vertical bar with it. Because the lookahead has its own parentheses. immediately followed by the if part. then the regex engine will attempt to match the then part. . you can use the lookahead and lookbehind constructs.

Now it is instantly obvious that this regex matches a date in yyyy-mm-dd format.](?#day)(0[1-9]|[12][0-9]|3[01])».80 20.g. Adding Comments to Regular Expressions If you have worked through the entire tutorial. many modern regex flavors allow you to insert comments into regexes. enabling the right comment in the right spot to make a complex regular expression much easier to understand. I could clarify the regex to match a valid date by writing it as «(?#year)(19|20)\d\d[/. as long as it does not contain a closing round bracket. E. That makes the comments really stand out. The syntax is «(?#comment)» where “comment” is be whatever you want./. The regex engine ignores everything after the «(?#» until the first closing round bracket. . Some software. EditPad Pro and PowerGREP can apply syntax coloring to regular expressions while you write them. I guess you will agree that regular expressions can quickly become rather cryptic.](?#month)(0[1-9]|1[012])[. such as RegexBuddy. Therefore.

Sign up to vote on this title
UsefulNot useful