Difference between revisions of "ReNamer:Regular Expressions"
(replacing <span color> with <span class>, replacing (0x201C and 0x201D) quotes with normal (0x22)) |
(further cleanup, more needs to be done) |
||
Line 2: | Line 2: | ||
* Replace all span color highlights with custom '''hl-*''' classes found in [[MediaWiki:Common.css]].(krtek: probably already done) | * Replace all span color highlights with custom '''hl-*''' classes found in [[MediaWiki:Common.css]].(krtek: probably already done) | ||
* Replace all '''""''' (0x201C and 0x201D) quotes with normal '''""''' (0x22). (krtek: probably already done) | * Replace all '''""''' (0x201C and 0x201D) quotes with normal '''""''' (0x22). (krtek: probably already done) | ||
+ | * Get rid of not needed <nowiki>'''</nowiki> wiki style bold around span '''hl-*''' classes, which are bold by definition (den4b: 40% done) | ||
* Check for italized " (quotes) and make them normal. Especially ending quotes got italized or bolded. | * Check for italized " (quotes) and make them normal. Especially ending quotes got italized or bolded. | ||
* }} | * }} | ||
Line 10: | Line 11: | ||
*The specified text must occur ''n'' times, etc. | *The specified text must occur ''n'' times, etc. | ||
− | RegEx expressions use <span class="hl-orange"> | + | RegEx expressions use <span class="hl-orange">$ . ^ { [ ( | ) * + ? \</span> characters (called ''metacharacters'') in various combinations to specify all these conditions.The search engine ''interprets'' these metacharacters, rather than finding a literal match for them. |
− | The RegEx search expression is called a "'''''RegEx pattern"''''', because a single expression can match a large number of actual text that has the specified ''pattern.'' For example, the RegEx pattern <span class="hl-orange"> | + | The RegEx search expression is called a "'''''RegEx pattern"''''', because a single expression can match a large number of actual text that has the specified ''pattern.'' For example, the RegEx pattern <span class="hl-orange">b?t</span> matches with '''bat''', '''bet''', '''bit''', '''bot''' and '''but''', etc. |
− | Remember that RegEx strings are case-sensitive (The words<span class="hl-orange"> | + | Remember that RegEx strings are case-sensitive (The words <span class="hl-orange">cat</span>, <span class="hl-orange">CAT</span>, <span class="hl-orange">cAt</span>, <span class="hl-orange">Cat</span>, <span class="hl-orange">caT</span>, <span class="hl-orange">cAT</span>, <span class="hl-orange">CAt</span> and <span class="hl-orange">CaT</span> are not equivalent). |
Also, note that even the digits (<span class="hl-orange">0</span>-<span class="hl-orange">9</span>) are "numeric characters" for RegEx. | Also, note that even the digits (<span class="hl-orange">0</span>-<span class="hl-orange">9</span>) are "numeric characters" for RegEx. | ||
− | In this section, the RegEx expressions (patterns) are shown in <span class="hl-orange"> | + | In this section, the RegEx expressions (patterns) are shown in <span class="hl-orange">bold orange</span>. The target strings (which are compared with the RegEx expression for a possible match) are shown in '''bold black'''. A part of the target text is color-coded to provide a clue as to why a certain part matches (<span class="hl-teal">green</span> color), or does <u>not</u> match (<span class="hl-red">red</span> color) |
=== Simple (literal) matches === | === Simple (literal) matches === | ||
Line 24: | Line 25: | ||
When the search string does not contain any metacharacters, the RegEx engine works like "normal" search. (it tries to find an exact copy of the search string.) (This is also known as "literal match"). | When the search string does not contain any metacharacters, the RegEx engine works like "normal" search. (it tries to find an exact copy of the search string.) (This is also known as "literal match"). | ||
− | If you want to find a literal match for a metacharacter, put a backslash '''\''' ''before'' it. (The | + | If you want to find a literal match for a metacharacter, put a backslash '''\''' ''before'' it. (The <span class="hl-orange">\</span> character is called "''escape character''", because it lets the metacharacter escape from its special duty, and lets it act as a normal character. Its combination with a metacharacter is called "''escape sequence''"). |
− | For example, metacharacter | + | For example, metacharacter <span class="hl-orange">^</span> matches the beginning of string, but <span class="hl-orange">\^</span> matches the character <span class="hl-teal">^</span>. |
− | Note that the RegEx pattern | + | Note that the RegEx pattern <span class="hl-orange">\\</span> matches the character <span class="hl-teal">\</span>. |
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx pattern | |
− | + | ! Matches | |
− | + | ! Remarks | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">foobar</span></center> |
− | | <center> | + | | <center><span class="hl-teal">foobar</span></center> |
| This RegEx pattern does not contain any metacharacters; so all characters are matched literally. | | This RegEx pattern does not contain any metacharacters; so all characters are matched literally. | ||
|- | |- | ||
− | | | + | | <center><span class="hl-orange">\^FooBarPtr</span></center> |
− | | <center> | + | | <center><span class="hl-teal">^FooBarPtr</span></center> |
− | | The | + | | The <span class="hl-orange">\^</span> escape sequence searches for the character '''^''' ''literally'' . |
|} | |} | ||
Line 51: | Line 52: | ||
Specific escape sequences are interpreted as special conditions, as listed below. | Specific escape sequences are interpreted as special conditions, as listed below. | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx pattern | |
− | + | ! matches | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\xnn</span></center> |
| Character represented by the hex code ''nn'' | | Character represented by the hex code ''nn'' | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\x{nnnn}</span></center> |
| two bytes char with hex code nnnn (unicode) | | two bytes char with hex code nnnn (unicode) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\t</span></center> |
| tab (HT/TAB), same as \x09 (Hex 09) | | tab (HT/TAB), same as \x09 (Hex 09) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\n</span></center> |
| new line (NL), same as \x0a (Hex 0a) | | new line (NL), same as \x0a (Hex 0a) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\r</span></center> |
| carriage return (CR), same as \x0d (Hex 0d) | | carriage return (CR), same as \x0d (Hex 0d) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\f</span></center> |
| form feed (FF), same as \x0c (Hex 0c) | | form feed (FF), same as \x0c (Hex 0c) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">foo\x20bar</span></center> |
− | | matches | + | | matches <span class="hl-teal">foo bar</span> (note the space in the middle), but does ''not'' match '''foobar''' |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\tfoobar</span></center> |
− | | matches | + | | matches <span class="hl-teal">foobar</span> preceded by a tab (the tab is needed for the match) |
|} | |} | ||
Line 85: | Line 86: | ||
=== Character Classes === | === Character Classes === | ||
− | A character class is a list of characters in square brackets | + | A character class is a list of characters in square brackets <span class="hl-orange">[]</span>, which will match any one (and ''only one''-) character from the list. |
− | Note that | + | Note that: |
− | *The characters are not separated with a comma or a space. | + | * The characters are not separated with a comma or a space. |
− | *If you repeat any character in the list, it is considered only once (duplicates are ignored). | + | * If you repeat any character in the list, it is considered only once (duplicates are ignored). |
− | *A hyphen | + | * A hyphen <span class="hl-orange">-</span> is used to indicate range of characters. |
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[abdef]</span></center> |
− | | Matches | + | | Matches <span class="hl-teal">d</span>, <span class="hl-teal">e</span>, or <span class="hl-teal">f</span> (only ''one'' character), but no other characters |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[c-m]</span></center> |
− | | Matches any one (and only one) of the small alphabetical characters, from | + | | Matches any one (and only one) of the small alphabetical characters, from <span class="hl-teal">c</span> to <span class="hl-teal">m</span> |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[G-J]</span></center> |
− | | Matches any one (and only one) of the capital alphabetical characters from | + | | Matches any one (and only one) of the capital alphabetical characters from <span class="hl-teal">G</span> to <span class="hl-teal">J</span> |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[a-zA-Z]</span></center> |
| Matches any one (and only one) of the alphabetical characters (capital or small) | | Matches any one (and only one) of the alphabetical characters (capital or small) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[5-8]</span></center> |
− | | Matches any one (and only one) of numerical characters from | + | | Matches any one (and only one) of numerical characters from <span class="hl-teal">5</span> to <span class="hl-teal">8</span> |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[\n-\x0D]</span></center> |
| | | | ||
− | Matches any one (and only one) of | + | Matches any one (and only one) of <span class="hl-teal">#10</span>, <span class="hl-teal">#11</span>, <span class="hl-teal">#12</span> or <span class="hl-teal">#13</span><br>(Note the use of [[ReNamer:Regular Expressions#Simple_.28literal.29_matches|escape sequence]] inside a class) |
|} | |} | ||
Line 121: | Line 122: | ||
There are some special conditions: | There are some special conditions: | ||
− | *If you do not want any of the characters in the specified class, then place | + | *If you do not want any of the characters in the specified class, then place <span class="hl-orange">^</span> at the very beginning of the list (RegEx interprets that as "none of the characters listed in this class"). |
− | *If you want | + | *If you want <span class="hl-orange">[</span> or <span class="hl-orange">]</span> itself to be a member of a class, put it at the start or end of the list, or create a [[ReNamer:Regular Expressions#Simple_.28literal.29_matches|escape sequence]] (by putting <span class="hl-orange">\</span> before it). |
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[-az]</span></center> |
| matches '''<span class="hl-teal">a</span>'','''''<i><span class="hl-teal">z</span>''', and '''<span class="hl-teal">-</span></i>'''<br>'''(since '''<span class="hl-orange">–</span>''' is put at the beginning, the escape sequence is not needed) | | matches '''<span class="hl-teal">a</span>'','''''<i><span class="hl-teal">z</span>''', and '''<span class="hl-teal">-</span></i>'''<br>'''(since '''<span class="hl-orange">–</span>''' is put at the beginning, the escape sequence is not needed) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[a\-z]</span></center> |
| matches '''<span class="hl-teal">a</span>'','''''<i><span class="hl-teal">z</span>''', and '''<span class="hl-teal">-</span></i>''' ''' <br>(since '''<span class="hl-orange">–</span>''' is ''not'' at the beginning/end, the escape sequence ''is'' needed) | | matches '''<span class="hl-teal">a</span>'','''''<i><span class="hl-teal">z</span>''', and '''<span class="hl-teal">-</span></i>''' ''' <br>(since '''<span class="hl-orange">–</span>''' is ''not'' at the beginning/end, the escape sequence ''is'' needed) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[^0-9]</span></center> |
| matches any ''non-digit'' character | | matches any ''non-digit'' character | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">[]-a]</span></center> |
| matches any character from '''<span class="hl-teal">]</span>''' to '''<span class="hl-teal">a</span>'''. <br>(since '''<span class="hl-orange">]</span> '''is at the beginning, the escape sequence ''is'' ''not'' needed) | | matches any character from '''<span class="hl-teal">]</span>''' to '''<span class="hl-teal">a</span>'''. <br>(since '''<span class="hl-orange">]</span> '''is at the beginning, the escape sequence ''is'' ''not'' needed) | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">foob[aeiou]r</span></center> |
| Matches with '''foob'''''<span class="hl-teal">a</span>'''''r''', '''foob'''''<span class="hl-teal">e</span>'''''r,''' etc. but not '''foob'''''<span class="hl-red">b</span>'''''r''', '''foob'''''<span class="hl-red">c</span>'''''r''', etc. | | Matches with '''foob'''''<span class="hl-teal">a</span>'''''r''', '''foob'''''<span class="hl-teal">e</span>'''''r,''' etc. but not '''foob'''''<span class="hl-red">b</span>'''''r''', '''foob'''''<span class="hl-red">c</span>'''''r''', etc. | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">foob[^aeiou]r</span></center> |
| Matches with '''foob'''''<span class="hl-teal">b</span>'''''r''', '''foob'''''<span class="hl-teal">c</span>'''''r''' etc. but not '''foob'''''<span class="hl-red">a</span>'''''r''', '''foob'''''<span class="hl-red">e</span>'''''r''', etc. | | Matches with '''foob'''''<span class="hl-teal">b</span>'''''r''', '''foob'''''<span class="hl-teal">c</span>'''''r''' etc. but not '''foob'''''<span class="hl-red">a</span>'''''r''', '''foob'''''<span class="hl-red">e</span>'''''r''', etc. | ||
|} | |} | ||
Line 154: | Line 155: | ||
Some of the character classes are used so often that RegEx has predefined escape sequences to represent them. | Some of the character classes are used so often that RegEx has predefined escape sequences to represent them. | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\w</span></center> |
| an alphanumeric character, including an ''underscore'' ('''_''') | | an alphanumeric character, including an ''underscore'' ('''_''') | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\W</span></center> |
| a non-alphanumeric character | | a non-alphanumeric character | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\d</span></center> |
| a numeric character | | a numeric character | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\D</span></center> |
| a non-numeric character | | a non-numeric character | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\s</span></center> |
− | | any space (same as the | + | | any space (same as the <span class="hl-orange">[ \t\n\r\f]</span> class) |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\S</span></center> |
| a non space | | a non space | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">.</span></center> |
| any character in line (the symbol is just a dot) | | any character in line (the symbol is just a dot) | ||
|} | |} | ||
− | Notice that the capitalized letter is used to negate (for example, compare | + | Notice that the capitalized letter is used to negate (for example, compare <span class="hl-orange">\w</span> with <span class="hl-orange">\W</span>) |
=== Word/Text Boundaries === | === Word/Text Boundaries === | ||
Line 187: | Line 188: | ||
A word boundary (<span class="hl-orange">\b</span>) is a spot between two characters that has a <span class="hl-orange">\w</span> on one side of it and a <span class="hl-orange">\W</span> on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a <span class="hl-orange">\W</span>. | A word boundary (<span class="hl-orange">\b</span>) is a spot between two characters that has a <span class="hl-orange">\w</span> on one side of it and a <span class="hl-orange">\W</span> on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a <span class="hl-orange">\W</span>. | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\b</span></center> |
| word boundary | | word boundary | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\B</span></center> |
| not word boundary | | not word boundary | ||
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\A</span></center> |
− | | start of text ( | + | | start of text (<span class="hl-orange">^</span> is an alternative) |
|- | |- | ||
− | | <center> | + | | <center><span class="hl-orange">\Z</span></center> |
− | | end of text ( | + | | end of text (<span class="hl-orange">$</span> is an alternative) |
|} | |} | ||
− | These markers are combined with the search string to specify where exactly you want the search string to be. For example, | + | These markers are combined with the search string to specify where exactly you want the search string to be. For example, <span class="hl-orange">\bhis\b</span> will search for a whole word '''his''', but will ignore <span class="hl-red">t</span>'''his''', '''his'''<span class="hl-red">tory</span> or <span class="hl-red">w</span>his<span class="hl-red">tle</span>. |
=== Iterators (Quantifiers) === | === Iterators (Quantifiers) === | ||
Line 222: | Line 223: | ||
Note that a '''<span class="hl-orange">?</span> '''attached to a greedy expression makes it non-greedy. | Note that a '''<span class="hl-orange">?</span> '''attached to a greedy expression makes it non-greedy. | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | ! | + | ! RegEx pattern |
− | ! | + | ! Remarks |
− | ! | + | ! Greedy? |
− | ! | + | ! Remarks |
|- | |- | ||
| <center>'''<span class="hl-orange">*</span>'''</center> | | <center>'''<span class="hl-orange">*</span>'''</center> | ||
Line 292: | Line 293: | ||
Let us see some examples: | Let us see some examples: | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | ! | + | ! RegEx pattern |
− | ! | + | ! Remarks |
|- | |- | ||
| <center>'''<span class="hl-orange">foob.*r</span>'''</center> | | <center>'''<span class="hl-orange">foob.*r</span>'''</center> | ||
Line 328: | Line 329: | ||
Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. For example, when matching '''<span class="hl-orange">foo|foot</span>''' against '''barefoot,''' only the '''foo '''part will match, because that is the first alternative tried, and it successfully matches the target string. (This is important when you are capturing matched text using parentheses.) | Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. For example, when matching '''<span class="hl-orange">foo|foot</span>''' against '''barefoot,''' only the '''foo '''part will match, because that is the first alternative tried, and it successfully matches the target string. (This is important when you are capturing matched text using parentheses.) | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
| '''<span class="hl-orange">foo(bar|foo)</span>''' | | '''<span class="hl-orange">foo(bar|foo)</span>''' | ||
Line 350: | Line 351: | ||
Let us see some examples: | Let us see some examples: | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
− | + | ! RegEx Pattern | |
− | + | ! Remarks | |
|- | |- | ||
| <center>'''<span class="hl-orange">(fee)|(fie)|(foe)</span>'''</center> | | <center>'''<span class="hl-orange">(fee)|(fie)|(foe)</span>'''</center> | ||
Line 370: | Line 371: | ||
|} | |} | ||
− | === Backreferences | + | === Backreferences === |
You must have told (or heard-) jokes like this one: | You must have told (or heard-) jokes like this one: | ||
Line 395: | Line 396: | ||
The backreferences can be used to compose the RegEx pattern itself, as shown below: | The backreferences can be used to compose the RegEx pattern itself, as shown below: | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
| <center>'''<span class="hl-orange">(.)\1+</span>'''</center> | | <center>'''<span class="hl-orange">(.)\1+</span>'''</center> | ||
Line 424: | Line 425: | ||
Here are some "find-and-replace" examples: | Here are some "find-and-replace" examples: | ||
− | {| class=" | + | {| class="wikitable" |
|- | |- | ||
! Expression | ! Expression | ||
Line 454: | Line 455: | ||
=== External links === | === External links === | ||
− | *[http://www.regular-expressions.info/ www.regular-expressions.info] | + | * [http://www.regular-expressions.info/ www.regular-expressions.info] |
− | **Excellent site devoted to regular expressions. Nicely structured and with many easy-to-understand examples. | + | ** Excellent site devoted to regular expressions. Nicely structured and with many easy-to-understand examples. |
− | *[http://www.regexpstudio.com/ www.regexpstudio.com] | + | * [http://www.regexpstudio.com/ www.regexpstudio.com] |
− | **Freeware regular expressions library for Delphi. | + | ** Freeware regular expressions library for Delphi. |
Revision as of 11:16, 30 August 2009
Regular Expressions (RegEx) allow you to use precise search conditions, such as:
- Your search string must be located at the beginning (or at the end) of a line,
- The specified text must occur n times, etc.
RegEx expressions use $ . ^ { [ ( | ) * + ? \ characters (called metacharacters) in various combinations to specify all these conditions.The search engine interprets these metacharacters, rather than finding a literal match for them.
The RegEx search expression is called a "RegEx pattern", because a single expression can match a large number of actual text that has the specified pattern. For example, the RegEx pattern b?t matches with bat, bet, bit, bot and but, etc.
Remember that RegEx strings are case-sensitive (The words cat, CAT, cAt, Cat, caT, cAT, CAt and CaT are not equivalent).
Also, note that even the digits (0-9) are "numeric characters" for RegEx.
In this section, the RegEx expressions (patterns) are shown in bold orange. The target strings (which are compared with the RegEx expression for a possible match) are shown in bold black. A part of the target text is color-coded to provide a clue as to why a certain part matches (green color), or does not match (red color)
Simple (literal) matches
When the search string does not contain any metacharacters, the RegEx engine works like "normal" search. (it tries to find an exact copy of the search string.) (This is also known as "literal match").
If you want to find a literal match for a metacharacter, put a backslash \ before it. (The \ character is called "escape character", because it lets the metacharacter escape from its special duty, and lets it act as a normal character. Its combination with a metacharacter is called "escape sequence").
For example, metacharacter ^ matches the beginning of string, but \^ matches the character ^.
Note that the RegEx pattern \\ matches the character \.
RegEx pattern | Matches | Remarks |
---|---|---|
This RegEx pattern does not contain any metacharacters; so all characters are matched literally. | ||
The \^ escape sequence searches for the character ^ literally . |
Escape sequences
We already saw one use of escape sequence (above).
Specific escape sequences are interpreted as special conditions, as listed below.
RegEx pattern | matches |
---|---|
Character represented by the hex code nn | |
two bytes char with hex code nnnn (unicode) | |
tab (HT/TAB), same as \x09 (Hex 09) | |
new line (NL), same as \x0a (Hex 0a) | |
carriage return (CR), same as \x0d (Hex 0d) | |
form feed (FF), same as \x0c (Hex 0c) | |
matches foo bar (note the space in the middle), but does not match foobar | |
matches foobar preceded by a tab (the tab is needed for the match) |
Note that the tab, new line, carriage return, and form feed are known as "white spaces". But RegEx can distinguish between them. This allows you to make high-precision searches.
Character Classes
A character class is a list of characters in square brackets [], which will match any one (and only one-) character from the list.
Note that:
- The characters are not separated with a comma or a space.
- If you repeat any character in the list, it is considered only once (duplicates are ignored).
- A hyphen - is used to indicate range of characters.
RegEx Pattern | Remarks |
---|---|
Matches d, e, or f (only one character), but no other characters | |
Matches any one (and only one) of the small alphabetical characters, from c to m | |
Matches any one (and only one) of the capital alphabetical characters from G to J | |
Matches any one (and only one) of the alphabetical characters (capital or small) | |
Matches any one (and only one) of numerical characters from 5 to 8 | |
Matches any one (and only one) of #10, #11, #12 or #13 |
There are some special conditions:
- If you do not want any of the characters in the specified class, then place ^ at the very beginning of the list (RegEx interprets that as "none of the characters listed in this class").
- If you want [ or ] itself to be a member of a class, put it at the start or end of the list, or create a escape sequence (by putting \ before it).
RegEx Pattern | Remarks |
---|---|
matches a,z, and - (since – is put at the beginning, the escape sequence is not needed) | |
matches a,z, and - (since – is not at the beginning/end, the escape sequence is needed) | |
matches any non-digit character | |
matches any character from ] to a. (since ] is at the beginning, the escape sequence is not needed) | |
Matches with foobar, foober, etc. but not foobbr, foobcr, etc. | |
Matches with foobbr, foobcr etc. but not foobar, foober, etc. |
@@@ The "]-a" example would need a clarification as to what is the natural sequence of characters, and where is a superset of all possible characters described?
Predefined Classes
Some of the character classes are used so often that RegEx has predefined escape sequences to represent them.
RegEx Pattern | Remarks |
---|---|
an alphanumeric character, including an underscore (_) | |
a non-alphanumeric character | |
a numeric character | |
a non-numeric character | |
any space (same as the [ \t\n\r\f] class) | |
a non space | |
any character in line (the symbol is just a dot) |
Notice that the capitalized letter is used to negate (for example, compare \w with \W)
Word/Text Boundaries
A word boundary (\b) is a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W.
RegEx Pattern | Remarks |
---|---|
word boundary | |
not word boundary | |
start of text (^ is an alternative) | |
end of text ($ is an alternative) |
These markers are combined with the search string to specify where exactly you want the search string to be. For example, \bhis\b will search for a whole word his, but will ignore this, history or whistle.
Iterators (Quantifiers)
Iterators (quantifiers) are meta-characters that specify how many times the preceding expression has to repeat, A typical example is to find a 3-to-5 digit number.
RegEx newbies often place the iterators after the character that needs to repeat. Just remember that RegEx syntax is exact opposite of the usual English syntax. So, instead of "four dogs", we would have to say "dogs four", RegEx-style.
Iterators can be 'Greedy' or 'Non-Greedy'. Greedy means the expression grabs as much matching text as possible. In contrast, the non-greedy expression tries to match as little as possible.
For example,
- when b+ (a greedy expression) is applied to string abbbbc, it returns bbbb,
- but when b+? (a non-greedy expression) is applied to abbbbc, it returns only b.
Note that a ? attached to a greedy expression makes it non-greedy.
RegEx pattern | Remarks | Greedy? | Remarks |
---|---|---|---|
zero or more | equivalent to {0,} | ||
one or more | equivalent to {1,} | ||
zero or one | equivalent to {0,1} | ||
exactly n times | |||
at least n times | |||
at least n but not more than m times | |||
zero or more | equivalent to {0,}? | ||
one or more | equivalent to {1,}? | ||
zero or one | equivalent to {0,1}? | ||
exactly n times | |||
at least n times | |||
at least n but not more than m times |
Let us see some examples:
RegEx pattern | Remarks |
---|---|
matches foobar, foobalkjdflkj9r and foobr | |
matches foobar, foobalkjdflkj9r but not foobr | |
matches foobar, foobbr and foobr but not foobalkj9r | |
matches foobaar | |
matches foobaar, foobaaar, foobaaaar etc. but not foobar | |
matches foobaar, or foobaaar but not foobaaaar or foobar |
Alternatives
A RegEx expression can have multiple alternative characters or subexpressions. The metacharacter | is used to separate the alternatives.
For example, fee|fie|foe will match with fee, fie, or foe in the target string.
It is difficult to understand where each alternative starts and ends. This is why it is a common practice to include alternatives in parentheses, to make it easier to understand.
For example, fee|fie|foe can be written as f(e|i|o)e, to make it easier to understand.
Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. For example, when matching foo|foot against barefoot, only the foo part will match, because that is the first alternative tried, and it successfully matches the target string. (This is important when you are capturing matched text using parentheses.)
RegEx Pattern | Remarks |
---|---|
foo(bar|foo) | matches foobar or foofoo |
Also remember that alternatives cannot be used inside a character class (square brackets), because | is interpreted as a literal within []. That means [fee|fie|foe] is same as [feio|]. (The other characters are treated as duplicates, and ignored).
Subexpressions
Parts of any RegEx pattern can be enclosed in brackets (), just like using brackets in a mathematics formula. Each part that is enclosed in brackets is called a "subexpression".
The brackets serve two main purposes:
- Better readability, as in the mathematical formula a+(b+c).
- Make a functional group, as in the mathematical formula a(b+c). This group is evaluated first.
Let us see some examples:
RegEx Pattern | Remarks |
---|---|
Much better readability than the equivalent RegEx pattern fee|fie|foe. | |
Matches with the entire enclosed string foobar repeated 2 or 3 times.
(i.e., matches with foobarfoobar or foobarfoobarfoobar) | |
Matches with fooba followed by the character r repeated 2 or 3 times. (i.e., matches with foobarr or foobarrr) (The iterator acts only on the last character.) | |
foob([0-9]|a+)r | matches only the character foob0r, foob1r , foobar, foobaar, foobaaaar, etc. (The subexpression is evaluated first.) |
Backreferences
You must have told (or heard-) jokes like this one:
"Two guys walk in a bar. The first guy says.... Then the second guy replies....".
Then you are already familiar with backreferences!
A "backreference" is a numbered reference to a previously mentioned thing.
RegEx also has backreferences. Let us understand how backreferences are defined in RegEx.
The RegEx engine tries to find text that matches the whole RegEx pattern. If a matching text is found, the RegEx engine identifies the matching text for each of the subexpressions in the pattern.
At this stage, the RegEx engine gives numbers to these matching parts:
- The text that matches the entire RegEx expression takes the number '0'.
- The text matching any subexpression is given a number based on the position of that subexpression inside the pattern. In other words, text matching the nth subexpression will take the number 'n'.
Now we use those numbers to refer to the entire pattern and/or subexpressions. (That is why these numbers are called "backreference".)
The backreference to the nth subexpression is written as \n.
The backreferences can be used to compose the RegEx pattern itself, as shown below:
matches aaaa and cc (any single character that is repeated twice or more) | |
matches aaaa, cc, abababab, 123123
(a set of one or more characters, repeated twice or more) (The character-sets are alternately colored blue and pink for easy identification. Observe how a RegEx pattern can match quite different text! ) |
Substitution of text using backreference
The backreferences are also used in find-and-replace operations, to re-assemble new text from old.
- The expressions \1 through \9 serve as backreferences to the subexpressions found in the RegEx pattern. The expression \0 is used to represent the text that matches the whole RegEx pattern. These are used in the "find" part of the operation.
- The expressions $1 through $9 represent the actual text that matches the respective subexpressions.These are used in the "replace" part of the operation.
The replacement text is typically a combination of-
- The text that matched the subexpressions, and
- Some new text.
Note that the RegEx pattern may have some parts that are not enclosed in (). (In other words, it may have parts that are not subexpressions.) Such parts are not used in the replacement text.
Here are some "find-and-replace" examples:
Expression | Replace | Description |
---|---|---|
Switch two words around and put a comma after the resulting first word. Example: if input string is "John Smith", then output will be "Smith, John".
Notice that the replacement text also has additional literal text in the middle (comma and space). | ||
Find date sequences in dd-mm-yyyy format and reverse them into yyyy-mm-dd format. (e.g. 25-10-2007 is converted to 2007-10-25). Note: This is not a very robust example, because \d can represent any digit in range of 0-9. That means sequences like 99-99-9999 also will match this pattern, resulting in a problem. This in fact shows that you need to be careful with RegEx patterns! | ||
Remove the contents of the [...] (square brackets), and the brackets too. (Replace with nothing means deleting.) |
Limitations for binary data
One of the known limitation of RegEx engine when working with binary data is that the input string is not search beyond the first occurrence of NULL character (\x00). This would not affect file names because there are simply no NULL characters in them, but may affect parsing of binary content of files when working in Pascal Script for example.
External links
- www.regular-expressions.info
- Excellent site devoted to regular expressions. Nicely structured and with many easy-to-understand examples.
- www.regexpstudio.com
- Freeware regular expressions library for Delphi.