Regular expressions, or "regexps", provide a way to find patterns within text. This is useful in many contexts, for example:
.PP
<center>.nf
.TS
l - l. Validation A regexp can be used to check whether a piece of text meets some criteria, e.g. is an integer or contains no whitespace. Searching Regexps provide a much more powerful means of searching text than simple string matching does. For example we can create a regexp which says "find one of the words 'mail', 'letter' or 'correspondence' but not any of the words 'email', 'mailman' 'mailer', 'letterbox' etc." Search and Replace A regexp can be used to replace a pattern with a piece of text, for example replace all occurrences of '&' with '&' except where the '&' is already followed by 'amp;'. String Splitting
We present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation itself. TQRegExp is modeled on Perl's regexp language, and also fully supports Unicode. TQRegExp can also be used in the weaker 'wildcard' (globbing) mode which works in a similar way to command shells. A good text on regexps is \fIMastering Regular Expressions: Powerful Techniques for Perl and Other Tools\fR by Jeffrey E. Friedl, ISBN 1565922573.
In case of multi-threaded programming, note that TQRegExp depends on TQThreadStorage internally. For that reason, TQRegExp should only be used with threads started with TQThread, i.e. not with threads started with platform-specific APIs.
Characters and Abbreviations for Sets of Characters
.TP
Sets of Characters
.TP
Quantifiers
.TP
Capturing Text
.TP
Assertions
.TP
Wildcard Matching (globbing)
.TP
Notes for Perl Users
.TP
Code Examples
.SH "Introduction"
Regexps are built up from expressions, quantifiers, and assertions. The simplest form of expression is simply a character, e.g. \fBx\fR or \fB5\fR. An expression can also be a set of characters. For example, \fB[ABCD]\fR, will match an \fBA\fR or a \fBB\fR or a \fBC\fR or a \fBD\fR. As a shorthand we could write this as \fB[A-D]\fR. If we want to match any of the captital letters in the English alphabet we can write \fB[A-Z]\fR. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. \fBx{1,1}\fR means match an \fBx\fR which occurs at least once and at most once. We'll look at assertions and more complex expressions later.
.PP
Note that in general regexps cannot be used to check for balanced brackets or tags. For example if you want to match an opening html \fC<b>\fR and its closing \fC</b>\fR you can only use a regexp if you know that these tags are not nested; the html fragment, \fC<b>bold <b>bolder</b></b>\fR will not match as expected. If you know the maximum level of nesting it is possible to create a regexp that will match correctly, but for an unknown level of nesting, regexps will fail.
We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with \fB[0-9]{1,1}\fR which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes \fB[0-9]{1,2}\fR meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits \fIwithin\fR a string. To ensure that we match against the whole string we must use the anchor assertions. We need \fB^\fR (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need \fB$\fR (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is \fB^[0-9]{1,2}$\fR. Note that assertions, such as \fB^\fR and \fB$\fR, do not match any characters.
If you've seen regexps elsewhere they may have looked different from the ones above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. \fB[0-9]\fR can be replaced with the symbol \fB\\d\fR. The quantifier to match exactly one occurrence, \fB{1,1}\fR, can be replaced with the expression itself. This means that \fBx{1,1}\fR is exactly the same as \fBx\fR alone. So our 0 to 99 matcher could be written \fB^\\d{1,2}$\fR. Another way of writing it would be \fB^\\d\\d{0,1}$\fR, i.e. from the start of the string match a digit followed by zero or one digits. In practice most people would write it \fB^\\d\\d?$\fR. The \fB?\fR is a shorthand for the quantifier \fB{0,1}\fR, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp \fB^\\d\\d?$\fR means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string".
.PP
Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, \fBm{1,1}a{1,1}i{1,1}l{1,1}\fR, but since each expression itself is automatically quantified by \fB{1,1}\fR we can simply write this as \fBmail\fR; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for \fIalternation\fR, so our regexp now becomes \fBmail|letter|correspondence\fR which means match 'mail' \fIor\fR 'letter' \fIor\fR 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parentheses, \fB(mail|letter|correspondence)\fR. Parentheses have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to capture. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time \fB\\b\fR "word boundary": \fB\\b(mail|letter|correspondence)\\b\fR. This regexp means "match a word boundary followed by the expression in parentheses followed by another word boundary". The \fB\\b\fR assertion matches at a \fIposition\fR in the regexp not a \fIcharacter\fR in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string.
.PP
For our third example we want to replace ampersands with the HTML entity '&'. The regexp to match is simple: \fB&\fR, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: \fB&(?!amp;)\fR. The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must \fInot\fR follow the expression that preceeds it.
.PP
Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are \fB\b(Eric|Eirik)\b\fR and \fB\bEi?ri[ck]\b\fR. We need the word boundary '\\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'.
.PP
We will implement some the examples above in the code examples section.
.SH "Characters and Abbreviations for Sets of Characters"
<center>.nf
.TS
l
-
l.
Element Meaning
Any character represents itself unless it has a special
regexp meaning. Thus
A character that follows a backslash matches the character
itself except where mentioned below. For example if you
wished to match a literal caret at the beginning of a string
you would write
This matches the ASCII bell character (BEL, 0x07).
This matches the ASCII form feed character (FF, 0x0C).
This matches the ASCII line feed character (LF, 0x0A, Unix newline).
This matches the ASCII carriage return character (CR, 0x0D).
This matches the ASCII horizontal tab character (HT, 0x09).
This matches the ASCII vertical tab character (VT, 0x0B).
This matches the Unicode character corresponding to the
hexadecimal number hhhh (between 0x0000 and 0xFFFF). \0ooo
(i.e., \\zero ooo) matches the ASCII/Latin-1 character
corresponding to the octal number ooo (between 0 and 0377).
\fINote that the C++ compiler transforms backslashes in strings so to include a \fB\\fR in a regexp you will need to enter it twice, i.e. \fB\\\fR.\fR
.SH "Sets of Characters"
Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets.
.PP
<center>.nf
.TS
l - l. The caret negates the character set if it occurs as the first character, i.e. immediately after the opening square bracket. For example, The dash is used to indicate a range of characters, for example
.TE
.fi
</center>
.PP
Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, \fB[0-9]\fR matches a digit in Western alphabets but \fB\\d\fR matches a digit in \fIany\fR alphabet.
.PP
Note that in most regexp literature sets of characters are called" character classes".
.SH "Quantifiers"
By default an expression is automatically quantified by \fB{1,1}\fR, i.e. it should occur exactly once. In the following list \fB\fIE\fR\fR stands for any expression. An expression is a character or an abbreviation for a set of characters or a set of characters in square brackets or any parenthesised expression.
.PP
<center>.nf
.TS
l
-
l.
Matches zero or one occurrence of \fIE\fR. This quantifier
means "the previous expression is optional" since it will
match whether or not the expression occurs in the string. It
is the same as
Matches one or more occurrences of \fIE\fR. This is the same
as
Matches zero or more occurrences of \fIE\fR. This is the same
as
Matches exactly \fIn\fR occurrences of the expression. This
is the same as repeating the expression \fIn\fR times. For
example,
Matches at least \fIn\fR occurrences of the expression. This
is the same as
Matches at most \fIm\fR occurrences of the expression. This
is the same as
.TE
.fi
</center>
.PP
(MAXINT is implementation dependent but will not be smaller than 1024.)
.PP
If we wish to apply a quantifier to more than just the preceding character we can use parentheses to group characters together in an expression. For example, \fBtag+\fR matches a 't' followed by an 'a' followed by at least one 'g', whereas \fB(tag)+\fR matches at least one occurrence of 'tag'.
.PP
Note that quantifiers are "greedy". They will match as much text as they can. For example, \fB0+\fR will match as many zeros as it can from the first zero it finds, e.g. '2.<u>000</u>5'. Quantifiers can be made non-greedy, see setMinimal().
.SH "Capturing Text"
Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expression \fBmail|letter|correspondence\fR that matches a string we know that \fIone\fR of the words matched but not which one. Using parentheses allows us to "capture" whatever is matched within their bounds, so if we used \fB(mail|letter|correspondence)\fR and matched this regexp against the string "I sent you some email" we can use the cap() or capturedTexts() functions to extract the matched characters, in this case 'mail'.
.PP
We can use captured text within the regexp itself. To refer to the captured text we use \fIbackreferences\fR which are indexed from 1, the same as for cap(). For example we could search for duplicate words in a string using \fB\\b(\\w+)\\W+\1\\b\fR which means match a word boundary followed by one or more word characters followed by one or more non-word characters followed by the same text as the first parenthesised expression followed by a word boundary.
.PP
If we want to use parentheses purely for grouping and not for capturing we can use the non-capturing syntax, e.g. \fB(?:green|blue)\fR. Non-capturing parentheses begin '(?:' and end ')'. In this example we match either 'green' or 'blue' but we do not capture the match so we only know whether or not we matched but not which color we actually found. Using non-capturing parentheses is more efficient than using capturing parentheses since the regexp engine has to do less book-keeping.
.PP
Both capturing and non-capturing parentheses may be nested.
.SH "Assertions"
Assertions make some statement about the text at the point where they occur in the regexp but they do not match any characters. In the following list \fB\fIE\fR\fR stands for any expression.
.PP
<center>.nf
.TS
l - l. The caret signifies the beginning of the string. If you wish to match a literal The dollar signifies the end of the string. For example A word boundary. For example the regexp A non-word boundary. This assertion is true wherever Positive lookahead. This assertion is true if the expression matches at this point in the regexp. For example, Negative lookahead. This assertion is true if the expression does not match at this point in the regexp. For example,
.TE
.fi
</center>
.SH "Wildcard Matching (globbing)"
Most command shells such as \fIbash\fR or \fIcmd.exe\fR support "file globbing", the ability to identify a group of files by using wildcards. The setWildcard() function is used to switch between regexp and wildcard mode. Wildcard matching is much simpler than full regexps and has only four features:
.PP
<center>.nf
.TS
l
-
l.
Any character represents itself apart from those mentioned
below. Thus
This matches any single character. It is the same as
This matches zero or more of any characters. It is the
same as
.TE
.fi
</center>
.PP
For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with \fB*.html\fR. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'.
In TQRegExp, apart from within character classes, \fC^\fR always signifies the start of the string, so carets must always be escaped unless used for that purpose. In Perl the meaning of caret varies automagically depending on where it occurs so escaping it is rarely necessary. The same applies to \fC$\fR which in TQRegExp always signifies the end of the string.
TQRegExp's quantifiers are the same as Perl's greedy quantifiers. Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regexp \fBro+?m\fR requires:
In TQRegExp \fB.\fR matches any character, therefore all TQRegExp regexps have the equivalent of Perl's \fC/s\fR option. TQRegExp does not have an equivalent to Perl's \fC/m\fR option, but this can be emulated in various ways for example by splitting the input into lines or by looping with a regexp that searches for newlines.
Perl's extended \fC/x\fR syntax is not supported, nor are directives, e.g. (?i), or regexp comments, e.g. (?#comment). On the other hand, C++'s rules for literal strings can be used to achieve the same:
Both zero-width positive and zero-width negative lookahead assertions (?=pattern) and (?!pattern) are supported with the same syntax as Perl. Perl's lookbehind assertions, "independent" subexpressions and conditional expressions are not supported.
.PP
Non-capturing parentheses are also supported, with the same (?:pattern) syntax.
rx.search( "Hello world" ); // returns -1 (no match)
.br
rx.search( "This_is-OK" ); // returns 0 (matched at position 0)
.br
.fi
.PP
The second string matches '<u>This_is-OK</u>'. We've used the character set abbreviation '\\S' (non-whitespace) and the anchors to match strings which contain no whitespace.
.PP
In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email'
rx.search( "I sent you an email" ); // returns -1 (no match)
.br
rx.search( "Please write the letter" ); // returns 17
.br
.fi
.PP
The second string matches "Please write the <u>letter</u>". The word 'letter' is also captured (because of the parentheses). We can see what text we've captured like this:
This will capture the text from the first set of capturing parentheses (counting capturing left parentheses from left to right). The parentheses are counted from 1 since cap( 0 ) is the whole matched regexp (equivalent to '&' in most regexp engines).
int count = 0; // how many Eric and Eirik's we've counted
.br
while ( pos >= 0 ) {
.br
pos = rx.search( str, pos );
.br
if ( pos >= 0 ) {
.br
pos++; // move along in str
.br
count++; // count our Eric or Eirik
.br
}
.br
}
.br
.fi
.PP
We've used the search() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time \fCpos++\fR we could have written \fCpos += rx.matchedLength()\fR to skip over the already matched string. The count will equal 3, matching 'One <u>Eric</u> another <u>Eirik</u>, and an Ericsson. How many Eiriks, <u>Eric</u>?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries.
.PP
One common use of regexps is to split lines of delimited data into their component fields.
In this example our input lines have the format company name, web address and country. Unfortunately the regexp is rather long and not very versatile -- the code will break if we add any more fields. A simpler and better solution is to look for the separator, '\\t' in this case, and take the surrounding text. The TQStringList split() function can take a separator string or regexp as an argument and split a string accordingly.
rx.setWildcard( TRUE ); // now it's a valid wildcard regexp
.br
rx.exactMatch( "index.html" ); // returns TRUE
.br
rx.exactMatch( "default.htm" ); // returns FALSE
.br
rx.exactMatch( "readme.txt" ); // returns FALSE
.br
.fi
.PP
Wildcard matching can be convenient because of its simplicity, but any wildcard regexp can be defined using full regexps, e.g. \fB.*\.html$\fR. Notice that we can't match both \fC.html\fR and \fC.htm\fR files with a wildcard unless we use \fB*.htm*\fR which will also match 'test.html.bak'. A full regexp gives us the precision we need, \fB.*\.html?$\fR.
TQRegExp can match case insensitively using setCaseSensitive(), and can use non-greedy matching, see setMinimal(). By default TQRegExp uses full regexps but this can be changed with setWildcard(). Searching can be forward with search() or backward with searchRev(). Captured text can be accessed using capturedTexts() which returns a string list of all captured strings, or using cap() which returns the captured string for the given index. The pos() function takes a match index and returns the position in the string where the match was made (or -1 if there was no match).
Constructs a regular expression object for the given \fIpattern\fR string. The pattern must be given using wildcard notation if \fIwildcard\fR is TRUE (default is FALSE). The pattern is case sensitive, unless \fIcaseSensitive\fR is FALSE. Matching is greedy (maximal), but can be changed by calling setMinimal().
.PP
See also setPattern(), setCaseSensitive(), setWildcard(), and setMinimal().
Returns the text captured by the \fInth\fR subexpression. The entire match has index 0 and the parenthesized subexpressions have indices starting from 1 (excluding non-capturing parentheses).
The order of elements matched by cap() is as follows. The first element, cap(0), is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus cap(1) is the text of the first capturing parentheses, cap(2) is the text of the second, and so on.
.PP
Some patterns may lead to a number of matches which cannot be determined in advance, for example:
The first string in the list is the entire matched string. Each subsequent list element contains a string that matched a (capturing) subexpression of the regexp.
// list is now ( "36 inches", "36", " ", "inches", "es" )
.br
.fi
.PP
The above example also captures elements that may be present but which we have no interest in. This problem can be solved by using non-capturing parentheses:
Some regexps can match an indeterminate number of times. For example if the input string is "Offsets: 12 14 99 231 7" and the regexp, \fCrx\fR, is \fB(\d+)+\fR, we would hope to get a list of all the numbers matched. However, after calling \fCrx.search(str)\fR, capturedTexts() will return the list ( "12"," 12" ), i.e. the entire match was "12" and the first subexpression matched was "12". The correct approach is to use cap() in a loop.
.PP
The order of elements in the string list is as follows. The first element is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus capturedTexts()[1] is the text of the first capturing parentheses, capturedTexts()[2] is the text of the second and so on (corresponding to $1, $2, etc., in some other regexp languages).
.PP
See also cap(), pos(), exactMatch(), search(), and searchRev().
Returns TRUE if \fIstr\fR is matched exactly by this regular expression; otherwise returns FALSE. You can determine how much of the string was matched by calling matchedLength().
.PP
For a given regexp string, R, exactMatch("R") is the equivalent of search("^R$") since exactMatch() effectively encloses the regexp in the start of string and end of string anchors, except that it sets matchedLength() differently.
.PP
For example, if the regular expression is \fBblue\fR, then exactMatch() returns TRUE only for input \fCblue\fR. For inputs \fCbluebell\fR, \fCblutak\fR and \fClightblue\fR, exactMatch() returns FALSE and matchedLength() will return 4, 3 and 0 respectively.
.PP
Although const, this function sets matchedLength(), capturedTexts() and pos().
Returns TRUE if the pattern string is empty; otherwise returns FALSE.
.PP
If you call exactMatch() with an empty pattern on an empty string it will return TRUE; otherwise it returns FALSE since it operates over the whole string. If you call search() with an empty pattern on \fIany\fR string it will return the start offset (0 by default) because the empty pattern matches the 'emptiness' at the start of the string. In this case the length of the match returned by matchedLength() will be 0.
Returns TRUE if the regular expression is valid; otherwise returns FALSE. An invalid regular expression never matches.
.PP
The pattern \fB[a-z\fR is an example of an invalid pattern, since it lacks a closing square bracket.
.PP
Note that the validity of a regexp may also depend on the setting of the wildcard flag, for example \fB*.html\fR is a valid wildcard regexp but an invalid full regexp.
\fBThis function is obsolete.\fR It is provided to keep old source working. We strongly advise against using it in new code.
.PP
Attempts to match in \fIstr\fR, starting from position \fIindex\fR. Returns the position of the match, or -1 if there was no match.
.PP
The length of the match is stored in \fI*len\fR, unless \fIlen\fR is a null pointer.
.PP
If \fIindexIsStart\fR is TRUE (the default), the position \fIindex\fR in the string will match the start of string anchor, \fB^\fR, in the regexp, if present. Otherwise, position 0 in \fIstr\fR will match.
.PP
Use search() and matchedLength() instead of this function.
Copies the regular expression \fIrx\fR and returns a reference to the copy. The case sensitivity, wildcard and minimal matching options are also copied.
Returns the position of the \fInth\fR captured text in the searched string. If \fInth\fR is 0 (the default), pos() returns the position of the whole match.
rx.search( "Output /dev/null" ); // returns 7 (position of /dev/null)
.br
rx.pos( 0 ); // returns 7 (position of /dev/null)
.br
rx.pos( 1 ); // returns 8 (position of dev)
.br
rx.pos( 2 ); // returns 12 (position of null)
.br
.fi
.PP
For zero-length matches, pos() always returns -1. (For example, if cap(4) would return an empty string, pos(4) returns -1.) This is due to an implementation tradeoff.
.PP
See also capturedTexts(), exactMatch(), search(), and searchRev().
Attempts to find a match in \fIstr\fR from position \fIoffset\fR (0 by default). If \fIoffset\fR is -1, the search starts at the last character; if -2, at the next to last character; etc.
.PP
Returns the position of the first match, or -1 if there was no match.
.PP
The \fIcaretMode\fR parameter can be used to instruct whether \fB^\fR should match at index 0 or at \fIoffset\fR.
Attempts to find a match backwards in \fIstr\fR from position \fIoffset\fR. If \fIoffset\fR is -1 (the default), the search starts at the last character; if -2, at the next to last character; etc.
.PP
Returns the position of the first match, or -1 if there was no match.
.PP
The \fIcaretMode\fR parameter can be used to instruct whether \fB^\fR should match at index 0 or at \fIoffset\fR.
.PP
Although const, this function sets matchedLength(), capturedTexts() and pos().
.PP
\fBWarning:\fR Searching backwards is much slower than searching forwards.
Enables or disables minimal matching. If \fIminimal\fR is FALSE, matching is greedy (maximal) which is the default.
.PP
For example, suppose we have the input string "We must be <b>bold</b>, very <b>bold</b>!" and the pattern \fB<b>.*</b>\fR. With the default greedy (maximal) matching, the match is "We must be <u><b>bold</b>, very <b>bold</b></u>!". But with minimal (non-greedy) matching the first match is: "We must be <u><b>bold</b></u>, very <b>bold</b>!" and the second match is "We must be <b>bold</b>, very <u><b>bold</b></u>!". In practice we might use the pattern \fB<b>[^<]+</b>\fR instead, although this will still fail for nested tags.
.PP
See also minimal().
.PP
Examples:
.)l network/archivesearch/archivedialog.ui.h and regexptester/regexptester.cpp.