Qt 4.8
Public Types | Public Functions | Static Public Functions | Properties | Related Functions | List of all members
QRegExp Class Reference

The QRegExp class provides pattern matching using regular expressions. More...

#include <qregexp.h>

Public Types

enum  CaretMode { CaretAtZero, CaretAtOffset, CaretWontMatch }
 The CaretMode enum defines the different meanings of the caret (^) in a regular expression. More...
 
enum  PatternSyntax {
  RegExp, Wildcard, FixedString, RegExp2,
  WildcardUnix, W3CXmlSchema11
}
 The syntax used to interpret the meaning of the pattern. More...
 

Public Functions

QString cap (int nth=0) const
 Returns the text captured by the nth subexpression. More...
 
QString cap (int nth=0)
 
int captureCount () const
 Returns the number of captures contained in the regular expression. More...
 
QStringList capturedTexts () const
 Returns a list of the captured text strings. More...
 
QStringList capturedTexts ()
 
Qt::CaseSensitivity caseSensitivity () const
 Returns Qt::CaseSensitive if the regexp is matched case sensitively; otherwise returns Qt::CaseInsensitive. More...
 
QString errorString () const
 Returns a text string that explains why a regexp pattern is invalid the case being; otherwise returns "no error occurred". More...
 
QString errorString ()
 
bool exactMatch (const QString &str) const
 Returns true if str is matched exactly by this regular expression; otherwise returns false. More...
 
int indexIn (const QString &str, int offset=0, CaretMode caretMode=CaretAtZero) const
 Attempts to find a match in str from position offset (0 by default). More...
 
bool isEmpty () const
 Returns true if the pattern string is empty; otherwise returns false. More...
 
bool isMinimal () const
 Returns true if minimal (non-greedy) matching is enabled; otherwise returns false. More...
 
bool isValid () const
 Returns true if the regular expression is valid; otherwise returns false. More...
 
int lastIndexIn (const QString &str, int offset=-1, CaretMode caretMode=CaretAtZero) const
 Attempts to find a match backwards in str from position offset. More...
 
int matchedLength () const
 Returns the length of the last matched string, or -1 if there was no match. More...
 
QT_DEPRECATED int numCaptures () const
 Returns the number of captures contained in the regular expression. More...
 
bool operator!= (const QRegExp &rx) const
 Returns true if this regular expression is not equal to rx; otherwise returns false. More...
 
QRegExpoperator= (const QRegExp &rx)
 Copies the regular expression rx and returns a reference to the copy. More...
 
bool operator== (const QRegExp &rx) const
 Returns true if this regular expression is equal to rx; otherwise returns false. More...
 
QString pattern () const
 Returns the pattern string of the regular expression. More...
 
PatternSyntax patternSyntax () const
 Returns the syntax used by the regular expression. More...
 
int pos (int nth=0) const
 Returns the position of the nth captured text in the searched string. More...
 
int pos (int nth=0)
 
 QRegExp ()
 Constructs an empty regexp. More...
 
 QRegExp (const QString &pattern, Qt::CaseSensitivity cs=Qt::CaseSensitive, PatternSyntax syntax=RegExp)
 Constructs a regular expression object for the given pattern string. More...
 
 QRegExp (const QRegExp &rx)
 Constructs a regular expression as a copy of rx. More...
 
void setCaseSensitivity (Qt::CaseSensitivity cs)
 Sets case sensitive matching to cs. More...
 
void setMinimal (bool minimal)
 Enables or disables minimal matching. More...
 
void setPattern (const QString &pattern)
 Sets the pattern string to pattern. More...
 
void setPatternSyntax (PatternSyntax syntax)
 Sets the syntax mode for the regular expression. More...
 
void swap (QRegExp &other)
 Swaps regular expression other with this regular expression. More...
 
 ~QRegExp ()
 Destroys the regular expression and cleans up its internal data. More...
 

Static Public Functions

static QString escape (const QString &str)
 Returns the string str with every regexp special character escaped with a backslash. More...
 

Properties

QRegExpPrivatepriv
 

Related Functions

(Note that these are not member functions.)

QDataStreamoperator<< (QDataStream &out, const QRegExp &regExp)
 Writes the regular expression regExp to stream out. More...
 
QDataStreamoperator>> (QDataStream &in, QRegExp &regExp)
 Reads a regular expression from stream in into regExp. More...
 

Detailed Description

The QRegExp class provides pattern matching using regular expressions.

Note
This class or function is reentrant.

regular expression

A regular expression, or "regexp", is a pattern for matching substrings in a text. This is useful in many contexts, e.g.,

Validation A regexp can test whether a substring meets some criteria, e.g. is an integer or contains no whitespace.
Searching A regexp provides more powerful pattern matching than simple substring matching, e.g., match one of the words mail, letter or correspondence, but none of the words email, mailman, mailer, letterbox, etc.
Search and Replace A regexp can replace all occurrences of a substring with a different substring, e.g., replace all occurrences of & with &amp; except where the & is already followed by an amp;.
String Splitting A regexp can be used to identify where a string should be split apart, e.g. splitting tab-delimited strings.

A brief introduction to regexps is presented, a description of Qt's regexp language, some examples, and the function documentation itself. QRegExp is modeled on Perl's regexp language. It fully supports Unicode. QRegExp can also be used in a simpler, wildcard mode that is similar to the functionality found in command shells. The syntax rules used by QRegExp can be changed with setPatternSyntax(). In particular, the pattern syntax can be set to QRegExp::FixedString, which means the pattern to be matched is interpreted as a plain string, i.e., special characters (e.g., backslash) are not escaped.

A good text on regexps is {Mastering Regular Expressions} (Third Edition) by Jeffrey E. F. Friedl, ISBN 0-596-52812-4.

Introduction

Regexps are built up from expressions, quantifiers, and assertions. The simplest expression is a character, e.g. x or 5. An expression can also be a set of characters enclosed in square brackets. [ABCD] will match an A or a B or a C or a D. We can write this same expression as [A-D], and an experession to match any captital letter in the English alphabet is written as [A-Z].

A quantifier specifies the number of occurrences of an expression that must be matched. x{1,1} means match one and only one x. x{1,5} means match a sequence of x characters that contains at least one x but no more than five.

Note that in general regexps cannot be used to check for balanced brackets or tags. For example, a regexp can be written to match an opening html and its closing , if the tags are not nested, but if the tags are nested, that same regexp will match an opening tag with the wrong closing . For the fragment bold bolder, the first would be matched with the first , which is not correct. However, it is possible to write a regexp that will match nested brackets or tags correctly, but only if the number of nesting levels is fixed and known. If the number of nesting levels is not fixed and known, it is impossible to write a regexp that will not fail.

Suppose we want a regexp to match integers in the range 0 to 99. At least one digit is required, so we start with the expression [0-9]{1,1}, which matches a single digit exactly once. This regexp matches integers in the range 0 to 9. To match integers up to 99, increase the maximum number of occurrences to 2, so the regexp becomes [0-9]{1,2}. This regexp satisfies the original requirement to match integers from 0 to 99, but it will also match integers that occur in the middle of strings. If we want the matched integer to be the whole string, we must use the anchor assertions, ^ (caret) and $ (dollar). When ^ is the first character in a regexp, it means the regexp must match from the beginning of the string. When $ is the last character of the regexp, it means the regexp must match to the end of the string. The regexp becomes ^[0-9]{1,2}$. Note that assertions, e.g. ^ and $, do not match characters but locations in the string.

If you have seen regexps described elsewhere, they may have looked different from the ones shown here. This is because some sets of characters and some quantifiers are so common that they have been given special symbols to represent them. [0-9] can be replaced with the symbol \d. The quantifier to match exactly one occurrence, {1,1}, can be replaced with the expression itself, i.e. x{1,1} is the same as x. So our 0 to 99 matcher could be written as ^\d{1,2}$. It can also be written ^\d\d{0,1}$, i.e. From the start of the string, match a digit, followed immediately by 0 or 1 digits. In practice, it would be written as ^\d\d?$. The ? is shorthand for the quantifier {0,1}, i.e. 0 or 1 occurrences. ? makes an expression optional. The regexp ^\d\d?$ means From the beginning of the string, match one digit, followed immediately by 0 or 1 more digit, followed immediately by end of string.

To write a regexp that matches one of the words 'mail' or 'letter' or 'correspondence' but does not match words that contain these words, e.g., 'email', 'mailman', 'mailer', and 'letterbox', start with a regexp that matches 'mail'. Expressed fully, the regexp is m{1,1}a{1,1}i{1,1}l{1,1}, but because a character expression is automatically quantified by {1,1}, we can simplify the regexp to mail, i.e., an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. Now we can use the vertical bar |, which means or, to include the other two words, so our regexp for matching any of the three words becomes mail|letter|correspondence. Match 'mail' or 'letter' or 'correspondence'. While this regexp will match one of the three words we want to match, it will also match words we don't want to match, e.g., 'email'. To prevent the regexp from matching unwanted words, we must tell it to begin and end the match at word boundaries. First we enclose our regexp in parentheses, (mail|letter|correspondence). Parentheses group expressions together, and they identify a part of the regexp that we wish to capturing text{capture}. Enclosing the expression in parentheses allows us to use it as a component in more complex regexps. It also allows us to examine which of the three words was actually matched. To force the match to begin and end on word boundaries, we enclose the regexp in \b word boundary assertions: \b(mail|letter|correspondence)\b. Now the regexp means: Match a word boundary, followed by the regexp in parentheses, followed by a word boundary. The \b assertion matches a position in the regexp, not a character. A word boundary is any non-word character, e.g., a space, newline, or the beginning or ending of a string.

If we want to replace ampersand characters with the HTML entity &amp;, the regexp to match is simply &. But this regexp will also match ampersands that have already been converted to HTML entities. We want to replace only ampersands that are not already followed by amp;. For this, we need the negative lookahead assertion, (?!__). The regexp can then be written as &(?!amp;), i.e. Match an ampersand that is not followed by amp;.

If we want to count all the occurrences of 'Eric' and 'Eirik' in a string, two valid solutions are \b(Eric|Eirik)\b and \bEi?ri[ck]\b. The word boundary assertion '\b' is required to avoid matching words that contain either name, e.g. 'Ericsson'. Note that the second regexp matches more spellings than we want: 'Eric', 'Erik', 'Eiric' and 'Eirik'.

Some of the examples discussed above are implemented in the code examples section.

Characters and Abbreviations for Sets of Characters

Element Meaning
c A character represents itself unless it has a special regexp meaning. e.g. c matches the character c.
\c A character that follows a backslash matches the character itself, except as specified below. e.g., To match a literal caret at the beginning of a string, write \^.
\a Matches the ASCII bell (BEL, 0x07).
\f Matches the ASCII form feed (FF, 0x0C).
\n Matches the ASCII line feed (LF, 0x0A, Unix newline).
\r Matches the ASCII carriage return (CR, 0x0D).
\t Matches the ASCII horizontal tab (HT, 0x09).
\v Matches the ASCII vertical tab (VT, 0x0B).
\xhhhh Matches the Unicode character corresponding to the hexadecimal number hhhh (between 0x0000 and 0xFFFF).
\0ooo (i.e., \zero ooo) matches the ASCII/Latin1 character for the octal number ooo (between 0 and 0377).
. (dot) Matches any character (including newline).
\d Matches a digit (QChar::isDigit()).
\D Matches a non-digit.
\s Matches a whitespace character (QChar::isSpace()).
\S Matches a non-whitespace character.
\w Matches a word character (QChar::isLetterOrNumber(), QChar::isMark(), or '_').
\W Matches a non-word character.
\n The n-th backreference , e.g. \1, \2, etc.

Note: The C++ compiler transforms backslashes in strings. To include a \ in a regexp, enter it twice, i.e. \. To match the backslash character itself, enter it four times, i.e. \\.

Sets of Characters

Square brackets mean match any character contained in the square brackets. The character set abbreviations described above can appear in a character set in square brackets. Except for the character set abbreviations and the following two exceptions, characters do not have special meanings in square brackets.

^

 <td> The caret negates the character set if it occurs as the
 first character (i.e. immediately after the opening square
 bracket). <b>[abc]</b> matches 'a' or 'b' or 'c', but
 <b>[^abc]</b> matches anything \e but 'a' or 'b' or 'c'.

-

 <td> The dash indicates a range of characters. <b>[W-Z]</b>
 matches 'W' or 'X' or 'Y' or 'Z'.

Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, [0-9] matches a digit in Western alphabets but \d matches a digit in any alphabet.

Note: In other regexp documentation, sets of characters are often called "character classes".

Quantifiers

By default, an expression is automatically quantified by {1,1}, i.e. it should occur exactly once. In the following list, {E} stands for expression. An expression is a character, or an abbreviation for a set of characters, or a set of characters in square brackets, or an expression in parentheses.

{E}?

 <td> Matches zero or one occurrences of \e E. This quantifier
 means <em>The previous expression is optional</em>, because it
 will match whether or not the expression is found. <b>\e
 {E}?</b> is the same as <b>\e {E}{0,1}</b>. e.g., <b>dents?</b>
 matches 'dent' or 'dents'.

{E}+

 <td> Matches one or more occurrences of \e E. <b>\e {E}+</b> is
 the same as <b>\e {E}{1,}</b>. e.g., <b>0+</b> matches '0',
 '00', '000', etc.

{E}*

 <td> Matches zero or more occurrences of \e E. It is the same
 as <b>\e {E}{0,}</b>. The <b>*</b> quantifier is often used
 in error where <b>+</b> should be used. For example, if
 <b>\\s*$</b> is used in an expression to match strings that
 end in whitespace, it will match every string because
 <b>\\s*$</b> means <em>Match zero or more whitespaces followed
 by end of string</em>. The correct regexp to match strings that
 have at least one trailing whitespace character is
 <b>\\s+$</b>.

{E}{n}

 <td> Matches exactly \e n occurrences of \e E. <b>\e {E}{n}</b>
 is the same as repeating \e E \e n times. For example,
 <b>x{5}</b> is the same as <b>xxxxx</b>. It is also the same
 as <b>\e {E}{n,n}</b>, e.g. <b>x{5,5}</b>.

{E}{n,}

Matches at least n occurrences of E.

{E}{,m}

Matches at most m occurrences of E. {E}{,m} is the same as {E}{0,m}.

{E}{n,m} Matches at least n and at most m occurrences of E.

To apply a quantifier to more than just the preceding character, use parentheses to group characters together in an expression. For example, tag+ matches a 't' followed by an 'a' followed by at least one 'g', whereas (tag)+ matches at least one occurrence of 'tag'.

Note: Quantifiers are normally "greedy". They always match as much text as they can. For example, 0+ matches the first zero it finds and all the consecutive zeros after the first zero. Applied to '20005', it matches'20005'. Quantifiers can be made non-greedy, see setMinimal().

Capturing Text

Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expression mail|letter|correspondence that matches a string we know that one of the words matched but not which one. Using parentheses allows us to "capture" whatever is matched within their bounds, so if we used (mail|letter|correspondence) 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'.

We can use captured text within the regexp itself. To refer to the captured text we use backreferences which are indexed from 1, the same as for cap(). For example we could search for duplicate words in a string using \b(\w+)\W+\1\b 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 parenthesized expression followed by a word boundary.

If we want to use parentheses purely for grouping and not for capturing we can use the non-capturing syntax, e.g. (?:green|blue). 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.

Both capturing and non-capturing parentheses may be nested.

For historical reasons, quantifiers (e.g. *) that apply to capturing parentheses are more "greedy" than other quantifiers. For example, a*(a*) will match "aaa" with cap(1) == "aaa". This behavior is different from what other regexp engines do (notably, Perl). To obtain a more intuitive capturing behavior, specify QRegExp::RegExp2 to the QRegExp constructor or call setPatternSyntax(QRegExp::RegExp2).

When the number of matches cannot be determined in advance, a common idiom is to use cap() in a loop. For example:

QRegExp rx("(\\d+)");
QString str = "Offsets: 12 14 99 231 7";
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
list << rx.cap(1);
pos += rx.matchedLength();
}
// list: ["12", "14", "99", "231", "7"]

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 {E} stands for any expression.

^

The caret signifies the beginning of the string. If you wish to match a literal ^ you must escape it by writing \^. For example, ^#include will only match strings which begin with the characters '#include'. (When the caret is the first character of a character set it has a special meaning, see Sets of Characters .)

$

The dollar signifies the end of the string. For example \d\s*$ will match strings which end with a digit optionally followed by whitespace. If you wish to match a literal $ you must escape it by writing \$.

\b

A word boundary. For example the regexp \bOK\b means match immediately after a word boundary (e.g. start of string or whitespace) the letter 'O' then the letter 'K' immediately before another word boundary (e.g. end of string or whitespace). But note that the assertion does not actually match any whitespace so if we write (\bOK\b) and we have a match it will only contain 'OK' even if the string is "It's <span style="text-decoration: underline;">OK</span> now".

\B

A non-word boundary. This assertion is true wherever \b is false. For example if we searched for \Bon\B in "Left on" the match would fail (space and end of string aren't non-word boundaries), but it would match in "t<span style="text-decoration: underline;">on</span>ne".

(?=E)

Positive lookahead. This assertion is true if the expression matches at this point in the regexp. For example, const(?=\s+char) matches 'const' whenever it is followed by 'char', as in 'static const char *'. (Compare with const\s+char, which matches 'static const char *'.)

(?!E) Negative lookahead. This assertion is true if the expression does not match at this point in the regexp. For example, const(?!\s+char) matches 'const' except when it is followed by 'char'.

QRegExp wildcard matching

Wildcard Matching

Most command shells such as bash or cmd.exe support "file globbing", the ability to identify a group of files by using wildcards. The setPatternSyntax() function is used to switch between regexp and wildcard mode. Wildcard matching is much simpler than full regexps and has only four features:

c Any character represents itself apart from those mentioned below. Thus c matches the character c.
? Matches any single character. It is the same as . in full regexps.
* Matches zero or more of any characters. It is the same as .* in full regexps.
[...] Sets of characters can be represented in square brackets, similar to full regexps. Within the character class, like outside, backslash has no special meaning.

In the mode Wildcard, the wildcard characters cannot be escaped. In the mode WildcardUnix, the character '\' escapes the wildcard.

For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with *.html. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'.

To test a string against a wildcard expression, use exactMatch(). For example:

QRegExp rx("*.txt");
rx.setPatternSyntax(QRegExp::Wildcard);
rx.exactMatch("README.txt"); // returns true
rx.exactMatch("welcome.txt.bak"); // returns false

Notes for Perl Users

Most of the character class abbreviations supported by Perl are supported by QRegExp, see characters and abbreviations for sets of characters .

In QRegExp, apart from within character classes, ^ 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 $ which in QRegExp always signifies the end of the string.

QRegExp's quantifiers are the same as Perl's greedy quantifiers (but see the greedy quantifiers{note above}). 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 ro+?m requires:

QRegExp rx("ro+m");
rx.setMinimal(true);

The equivalent of Perl's /i option is setCaseSensitivity(Qt::CaseInsensitive).

Perl's /g option can be emulated using a loop.

In QRegExp . matches any character, therefore all QRegExp regexps have the equivalent of Perl's /s option. QRegExp does not have an equivalent to Perl's /m 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.

Because QRegExp is string oriented, there are no \A, \Z, or \z assertions. The \G assertion is not supported but can be emulated in a loop.

Perl's $& is cap(0) or capturedTexts()[0]. There are no QRegExp equivalents for $`, $' or $+. Perl's capturing variables, $1, $2, ... correspond to cap(1) or capturedTexts()[1], cap(2) or capturedTexts()[2], etc.

To substitute a pattern use QString::replace().

Perl's extended /x 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:

QRegExp mark("\\b" // word boundary
"[Mm]ark" // the word we want to match
);

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.

Non-capturing parentheses are also supported, with the same (?:pattern) syntax.

See QString::split() and QStringList::join() for equivalents to Perl's split and join functions.

Note: because C++ transforms \'s they must be written twice in code, e.g. \b must be written \\b.

Code Examples

QRegExp rx("^\\d\\d?$"); // match integers 0 to 99
rx.indexIn("123"); // returns -1 (no match)
rx.indexIn("-6"); // returns -1 (no match)
rx.indexIn("6"); // returns 0 (matched as position 0)

The third string matches '6'. This is a simple validation regexp for integers in the range 0 to 99.

QRegExp rx("^\\S+$"); // match strings without whitespace
rx.indexIn("Hello world"); // returns -1 (no match)
rx.indexIn("This_is-OK"); // returns 0 (matched at position 0)

The second string matches 'This_is-OK'. We've used the character set abbreviation '\S' (non-whitespace) and the anchors to match strings which contain no whitespace.

In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email'

QRegExp rx("\\b(mail|letter|correspondence)\\b");
rx.indexIn("I sent you an email"); // returns -1 (no match)
rx.indexIn("Please write the letter"); // returns 17

The second string matches "Please write the <span style="text-decoration: underline;">letter</span>". The word 'letter' is also captured (because of the parentheses). We can see what text we've captured like this:

QString captured = rx.cap(1); // captured == "letter"

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).

QRegExp rx("&(?!amp;)"); // match ampersands but not &amp;
QString line1 = "This & that";
line1.replace(rx, "&amp;");
// line1 == "This &amp; that"
QString line2 = "His &amp; hers & theirs";
line2.replace(rx, "&amp;");
// line2 == "His &amp; hers &amp; theirs"

Here we've passed the QRegExp to QString's replace() function to replace the matched text with new text.

QString str = "One Eric another Eirik, and an Ericsson. "
"How many Eiriks, Eric?";
QRegExp rx("\\b(Eric|Eirik)\\b"); // match Eric or Eirik
int pos = 0; // where we are in the string
int count = 0; // how many Eric and Eirik's we've counted
while (pos >= 0) {
pos = rx.indexIn(str, pos);
if (pos >= 0) {
++pos; // move along in str
++count; // count our Eric or Eirik
}
}

We've used the indexIn() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time pos++ we could have written {pos += rx.matchedLength()} to skip over the already matched string. The count will equal 3, matching 'One Eric another Eirik, and an Ericsson. How many Eiriks, Eric?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries.

One common use of regexps is to split lines of delimited data into their component fields.

str = "Nokia Corporation\tqt.nokia.com\tNorway";
QString company, web, country;
rx.setPattern("^([^\t]+)\t([^\t]+)\t([^\t]+)$");
if (rx.indexIn(str) != -1) {
company = rx.cap(1);
web = rx.cap(2);
country = rx.cap(3);
}

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 QString::split() function can take a separator string or regexp as an argument and split a string accordingly.

QStringList field = str.split("\t");

Here field[0] is the company, field[1] the web address and so on.

To imitate the matching of a shell we can use wildcard mode.

QRegExp rx("*.html");
rx.setPatternSyntax(QRegExp::Wildcard);
rx.exactMatch("index.html"); // returns true
rx.exactMatch("default.htm"); // returns false
rx.exactMatch("readme.txt"); // returns false

Wildcard matching can be convenient because of its simplicity, but any wildcard regexp can be defined using full regexps, e.g. .*\.html$. Notice that we can't match both .html and .htm files with a wildcard unless we use *.htm* which will also match 'test.html.bak'. A full regexp gives us the precision we need, .*\.html?$.

QRegExp can match case insensitively using setCaseSensitivity(), and can use non-greedy matching, see setMinimal(). By default QRegExp uses full regexps but this can be changed with setWildcard(). Searching can be forward with indexIn() or backward with lastIndexIn(). 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).

See also
QString, QStringList, QRegExpValidator, QSortFilterProxyModel, {tools/regexp}{Regular Expression Example}

Definition at line 61 of file qregexp.h.

Enumerations

◆ CaretMode

The CaretMode enum defines the different meanings of the caret (^) in a regular expression.

The possible values are:

  • CaretAtZero The caret corresponds to index 0 in the searched string.
  • CaretAtOffset The caret corresponds to the start offset of the search.
  • CaretWontMatch The caret never matches.
Enumerator
CaretAtZero 
CaretAtOffset 
CaretWontMatch 

Definition at line 71 of file qregexp.h.

◆ PatternSyntax

The syntax used to interpret the meaning of the pattern.

  • RegExp A rich Perl-like pattern matching syntax. This is the default.
  • RegExp2 Like RegExp, but with greedy quantifiers. This will be the default in Qt 5. (Introduced in Qt 4.2.)
  • Wildcard This provides a simple pattern matching syntax similar to that used by shells (command interpreters) for "file globbing". See Wildcard Matching.
  • WildcardUnix This is similar to Wildcard but with the behavior of a Unix shell. The wildcard characters can be escaped with the character "\\".
  • FixedString The pattern is a fixed string. This is equivalent to using the RegExp pattern on a string in which all metacharacters are escaped using escape().
  • W3CXmlSchema11 The pattern is a regular expression as defined by the W3C XML Schema 1.1 specification.
See also
setPatternSyntax()
Enumerator
RegExp 
Wildcard 
FixedString 
RegExp2 
WildcardUnix 
W3CXmlSchema11 

Definition at line 64 of file qregexp.h.

Constructors and Destructors

◆ QRegExp() [1/3]

QRegExp::QRegExp ( )

Constructs an empty regexp.

See also
isValid(), errorString()

Definition at line 3807 of file qregexp.cpp.

3808 {
3809  priv = new QRegExpPrivate;
3811 }
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ QRegExp() [2/3]

QRegExp::QRegExp ( const QString pattern,
Qt::CaseSensitivity  cs = Qt::CaseSensitive,
PatternSyntax  syntax = RegExp 
)
explicit

Constructs a regular expression object for the given pattern string.

The pattern must be given using wildcard notation if syntax is Wildcard ; the default is RegExp . The pattern is case sensitive, unless cs is Qt::CaseInsensitive. Matching is greedy (maximal), but can be changed by calling setMinimal().

See also
setPattern(), setCaseSensitivity(), setPatternSyntax()

Definition at line 3823 of file qregexp.cpp.

3824 {
3825  priv = new QRegExpPrivate(QRegExpEngineKey(pattern, syntax, cs));
3827 }
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ QRegExp() [3/3]

QRegExp::QRegExp ( const QRegExp rx)

Constructs a regular expression as a copy of rx.

See also
operator=()

Definition at line 3834 of file qregexp.cpp.

3835 {
3836  priv = new QRegExpPrivate;
3837  operator=(rx);
3838 }
QRegExp & operator=(const QRegExp &rx)
Copies the regular expression rx and returns a reference to the copy.
Definition: qregexp.cpp:3854
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ ~QRegExp()

QRegExp::~QRegExp ( )

Destroys the regular expression and cleans up its internal data.

Definition at line 3843 of file qregexp.cpp.

3844 {
3846  delete priv;
3847 }
QRegExpPrivate * priv
Definition: qregexp.h:153
static void invalidateEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3742

Functions

◆ cap() [1/2]

QString QRegExp::cap ( int  nth = 0) const

Returns the text captured by the nth subexpression.

The entire match has index 0 and the parenthesized subexpressions have indexes starting from 1 (excluding non-capturing parentheses).

QRegExp rxlen("(\\d+)(?:\\s*)(cm|inch)");
int pos = rxlen.indexIn("Length: 189cm");
if (pos > -1) {
QString value = rxlen.cap(1); // "189"
QString unit = rxlen.cap(2); // "cm"
// ...
}

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.

See also
capturedTexts(), pos()

Definition at line 4310 of file qregexp.cpp.

Referenced by QUnixPrintWidgetPrivate::applyPrinterProperties(), colorFromName(), QQnxScreen::connect(), QVNCScreen::connect(), PvrEglScreen::connect(), QLinuxFbScreen::connect(), QLinuxFbIntegration::connect(), QDirectFBScreen::connect(), QGtkStylePrivate::extract_filter(), QBenchmarkValgrindUtils::extractResult(), filterDisplayOffset(), filterTransformation(), getDisplayId(), QBenchmarkValgrindUtils::getNewestFileName(), QPSQLDriverPrivate::getPSQLVersion(), QBenchmarkValgrindUtils::haveValgrind(), QAxServerBase::Invoke(), ShaderEffectItem::lookThroughShaderCode(), QWSServerPrivate::newMouseHandler(), QOCIDriver::open(), QTDSDriver::primaryIndex(), QSvgHandler::processingInstruction(), qt_clean_filter_list(), qt_getLprPrinters(), qt_init(), qt_mac_extract_filter(), qt_strip_filters(), qt_win_extract_filter(), qt_win_filter(), QWSPcMouseHandlerPrivate::QWSPcMouseHandlerPrivate(), QWSTslibMouseHandlerPrivate::QWSTslibMouseHandlerPrivate(), QNSOpenSavePanelDelegate::removeExtensions:, QString::replace(), QDomDocumentPrivate::saveDocument(), QDirectFBScreenPrivate::setFlipFlags(), and setIntOption().

4311 {
4312  return capturedTexts().value(nth);
4313 }
QStringList capturedTexts() const
Returns a list of the captured text strings.
Definition: qregexp.cpp:4267
T value(int i) const
Returns the value at index position i in the list.
Definition: qlist.h:661

◆ cap() [2/2]

QString QRegExp::cap ( int  nth = 0)
Warning
This function is not part of the public interface.

Definition at line 4318 of file qregexp.cpp.

4319 {
4320  return const_cast<const QRegExp *>(this)->cap(nth);
4321 }
QString cap(int nth=0) const
Returns the text captured by the nth subexpression.
Definition: qregexp.cpp:4310
The QRegExp class provides pattern matching using regular expressions.
Definition: qregexp.h:61

◆ captureCount()

int QRegExp::captureCount ( ) const

Returns the number of captures contained in the regular expression.

Since
4.6

Definition at line 4223 of file qregexp.cpp.

Referenced by QPatternist::PatternPlatform::captureCount(), colorFromName(), QPatternist::ReplaceFN::evaluateSingleton(), QBenchmarkValgrindUtils::extractResult(), and QString::replace().

4224 {
4226  return priv->eng->captureCount();
4227 }
int captureCount() const
Definition: qregexp.cpp:1085
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngine * eng
Definition: qregexp.cpp:3656

◆ capturedTexts() [1/2]

QStringList QRegExp::capturedTexts ( ) const

Returns a list of the captured text strings.

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.

For example:

QRegExp rx("(\\d+)(\\s*)(cm|inch(es)?)");
int pos = rx.indexIn("Length: 36 inches");
QStringList list = rx.capturedTexts();
// list is now ("36 inches", "36", " ", "inches", "es")

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:

QRegExp rx("(\\d+)(?:\\s*)(cm|inch(?:es)?)");
int pos = rx.indexIn("Length: 36 inches");
QStringList list = rx.capturedTexts();
// list is now ("36 inches", "36", "inches")

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

QStringList list = rx.capturedTexts();
while (it != list.end()) {
myProcessing(*it);
++it;
}

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, rx, is (\d+)+, we would hope to get a list of all the numbers matched. However, after calling rx.indexIn(str), 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.

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).

See also
cap(), pos()

Definition at line 4267 of file qregexp.cpp.

Referenced by QPatternist::AbstractDuration::create(), QPatternist::AbstractDateTime::create(), launchWebBrowser(), parseDateString(), QFtpDTP::parseDir(), QFtpPI::processReply(), and QScriptCompletionTask::start().

4268 {
4269  if (priv->capturedCache.isEmpty()) {
4271  const int *captured = priv->matchState.captured;
4272  int n = priv->matchState.capturedSize;
4273 
4274  for (int i = 0; i < n; i += 2) {
4275  QString m;
4276  if (captured[i + 1] == 0)
4277  m = QLatin1String(""); // ### Qt 5: don't distinguish between null and empty
4278  else if (captured[i] >= 0)
4279  m = priv->t.mid(captured[i], captured[i + 1]);
4281  }
4282  priv->t.clear();
4283  }
4284  return priv->capturedCache;
4285 }
QStringList capturedCache
Definition: qregexp.cpp:3661
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
QString mid(int position, int n=-1) const Q_REQUIRED_RESULT
Returns a string that contains n characters of this string, starting at the specified position index...
Definition: qstring.cpp:3706
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QRegExpPrivate * priv
Definition: qregexp.h:153
void clear()
Clears the contents of the string and makes it empty.
Definition: qstring.h:723

◆ capturedTexts() [2/2]

QStringList QRegExp::capturedTexts ( )
Warning
This function is not part of the public interface.

Definition at line 4290 of file qregexp.cpp.

4291 {
4292  return const_cast<const QRegExp *>(this)->capturedTexts();
4293 }
The QRegExp class provides pattern matching using regular expressions.
Definition: qregexp.h:61
QStringList capturedTexts() const
Returns a list of the captured text strings.
Definition: qregexp.cpp:4267

◆ caseSensitivity()

Qt::CaseSensitivity QRegExp::caseSensitivity ( ) const

Returns Qt::CaseSensitive if the regexp is matched case sensitively; otherwise returns Qt::CaseInsensitive.

See also
patternSyntax(), pattern(), isMinimal()

Definition at line 3985 of file qregexp.cpp.

Referenced by QScriptEnginePrivate::newRegExp(), and operator<<().

3986 {
3987  return priv->engineKey.cs;
3988 }
Qt::CaseSensitivity cs
Definition: qregexp.cpp:876
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657

◆ errorString() [1/2]

QString QRegExp::errorString ( ) const

Returns a text string that explains why a regexp pattern is invalid the case being; otherwise returns "no error occurred".

See also
isValid()

Definition at line 4359 of file qregexp.cpp.

Referenced by QPatternist::PatternPlatform::parsePattern().

4360 {
4361  if (isValid()) {
4362  return QString::fromLatin1(RXERR_OK);
4363  } else {
4364  return priv->eng->errorString();
4365  }
4366 }
bool isValid() const
Returns true if the regular expression is valid; otherwise returns false.
Definition: qregexp.cpp:3943
#define RXERR_OK
Definition: qregexp.cpp:65
QRegExpPrivate * priv
Definition: qregexp.h:153
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
const QString & errorString() const
Definition: qregexp.cpp:1084
QRegExpEngine * eng
Definition: qregexp.cpp:3656

◆ errorString() [2/2]

QString QRegExp::errorString ( )
Warning
This function is not part of the public interface.

Definition at line 4371 of file qregexp.cpp.

4372 {
4373  return const_cast<const QRegExp *>(this)->errorString();
4374 }
The QRegExp class provides pattern matching using regular expressions.
Definition: qregexp.h:61
QString errorString() const
Returns a text string that explains why a regexp pattern is invalid the case being; otherwise returns...
Definition: qregexp.cpp:4359

◆ escape()

QString QRegExp::escape ( const QString str)
static

Returns the string str with every regexp special character escaped with a backslash.

The special characters are $, (,), *, +, ., ?, [, \,], ^, {, | and }.

Example:

s1 = QRegExp::escape("bingo"); // s1 == "bingo"
s2 = QRegExp::escape("f(x)"); // s2 == "f\\(x\\)"

This function is useful to construct regexp patterns dynamically:

"|" + QRegExp::escape(alias) + ")");
See also
setPatternSyntax()

Definition at line 4392 of file qregexp.cpp.

Referenced by qt_regexp_toCanonical(), QFSCompleter::splitPath(), and QCompleter::splitPath().

4393 {
4394  QString quoted;
4395  const int count = str.count();
4396  quoted.reserve(count * 2);
4397  const QLatin1Char backslash('\\');
4398  for (int i = 0; i < count; i++) {
4399  switch (str.at(i).toLatin1()) {
4400  case '$':
4401  case '(':
4402  case ')':
4403  case '*':
4404  case '+':
4405  case '.':
4406  case '?':
4407  case '[':
4408  case '\\':
4409  case ']':
4410  case '^':
4411  case '{':
4412  case '|':
4413  case '}':
4414  quoted.append(backslash);
4415  }
4416  quoted.append(str.at(i));
4417  }
4418  return quoted;
4419 }
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
The QString class provides a Unicode character string.
Definition: qstring.h:83
void reserve(int size)
Attempts to allocate memory for at least size characters.
Definition: qstring.h:881
int count() const
Definition: qstring.h:103
QString & append(QChar c)
Definition: qstring.cpp:1777
char toLatin1() const
Returns the Latin-1 character equivalent to the QChar, or 0.
Definition: qchar.h:376
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ exactMatch()

bool QRegExp::exactMatch ( const QString str) const

Returns true if str is matched exactly by this regular expression; otherwise returns false.

You can determine how much of the string was matched by calling matchedLength().

For a given regexp string R, exactMatch("R") is the equivalent of indexIn("^R$") since exactMatch() effectively encloses the regexp in the start of string and end of string anchors, except that it sets matchedLength() differently.

For example, if the regular expression is blue, then exactMatch() returns true only for input blue. For inputs bluebell, blutak and lightblue, exactMatch() returns false and matchedLength() will return 4, 3 and 0 respectively.

Although const, this function sets matchedLength(), capturedTexts(), and pos().

See also
indexIn(), lastIndexIn()

Definition at line 4094 of file qregexp.cpp.

Referenced by QUnixPrintWidgetPrivate::applyPrinterProperties(), QPatternist::XsdTypeChecker::checkConstrainingFacetsBoolean(), QPatternist::XsdTypeChecker::checkConstrainingFacetsDateTime(), QPatternist::XsdTypeChecker::checkConstrainingFacetsDouble(), QPatternist::XsdTypeChecker::checkConstrainingFacetsDuration(), QPatternist::XsdTypeChecker::checkConstrainingFacetsList(), QPatternist::XsdTypeChecker::checkConstrainingFacetsQName(), QPatternist::XsdTypeChecker::checkConstrainingFacetsSignedInteger(), QPatternist::XsdTypeChecker::checkConstrainingFacetsString(), QPatternist::XsdTypeChecker::checkConstrainingFacetsUnion(), QPatternist::XsdTypeChecker::checkConstrainingFacetsUnsignedInteger(), colorFromName(), PvrEglScreen::connect(), QLinuxFbScreen::connect(), QLinuxFbIntegration::connect(), QDirectFBScreen::connect(), QPatternist::AbstractDuration::create(), QPatternist::AbstractDateTime::create(), QSslCertificate::fromPath(), indexOfMutating(), isBypassed(), QXmlUtils::isEncName(), isHostExcluded(), Maemo::ProxyConfPrivate::isHostExcluded(), lastIndexOfMutating(), QDir::match(), QPatternist::XsdSchemaParser::parseDocumentation(), QPatternist::XsdSchemaParser::parseSchema(), QFileDialogPrivate::qt_mac_filedialog_filter_proc(), QRegExpValidator::validate(), and QPatternist::yyparse().

4095 {
4097  priv->matchState.match(str.unicode(), str.length(), 0, priv->minimal, true, 0);
4098  if (priv->matchState.captured[1] == str.length()) {
4099  return true;
4100  } else {
4101  priv->matchState.captured[0] = 0;
4103  return false;
4104  }
4105 }
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
const QChar * unicode() const
Returns a &#39;\0&#39;-terminated Unicode representation of the string.
Definition: qstring.h:706
QRegExpPrivate * priv
Definition: qregexp.h:153
static void prepareEngineForMatch(QRegExpPrivate *priv, const QString &str)
Definition: qregexp.cpp:3730
void match(const QChar *str, int len, int pos, bool minimal, bool oneTest, int caretIndex)
Definition: qregexp.cpp:1414

◆ indexIn()

int QRegExp::indexIn ( const QString str,
int  offset = 0,
CaretMode  caretMode = CaretAtZero 
) const

Attempts to find a match in str from position offset (0 by default).

If offset is -1, the search starts at the last character; if -2, at the next to last character; etc.

Returns the position of the first match, or -1 if there was no match.

The caretMode parameter can be used to instruct whether ^ should match at index 0 or at offset.

You might prefer to use QString::indexOf(), QString::contains(), or even QStringList::filter(). To replace matches use QString::replace().

Example:

QString str = "offsets: 1.23 .50 71.00 6.00";
QRegExp rx("\\d*\\.\\d+"); // primitive floating point matching
int count = 0;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
++count;
pos += rx.matchedLength();
}
// pos will be 9, 14, 18 and finally 24; count will end up as 4

Although const, this function sets matchedLength(), capturedTexts() and pos().

If the QRegExp is a wildcard expression (see setPatternSyntax()) and want to test a string against the whole wildcard expression, use exactMatch() instead of this function.

See also
lastIndexIn(), exactMatch()

Definition at line 4136 of file qregexp.cpp.

Referenced by QString::count(), QGtkStylePrivate::extract_filter(), QBenchmarkValgrindUtils::extractResult(), fbname(), filterDisplayOffset(), filterTransformation(), findInBlock(), QBenchmarkValgrindUtils::getNewestFileName(), QPSQLDriverPrivate::getPSQLVersion(), QBenchmarkValgrindUtils::haveValgrind(), QString::indexOf(), QObject::killTimer(), launchWebBrowser(), QLibraryInfo::location(), ShaderEffectItem::lookThroughShaderCode(), QWSServerPrivate::newMouseHandler(), QOCIDriver::open(), parseDateString(), QFtpDTP::parseDir(), QTDSDriver::primaryIndex(), QSvgHandler::processingInstruction(), QFtpPI::processReply(), qt_clean_filter_list(), qt_getLprPrinters(), qt_mac_extract_filter(), qt_qFindChildren_helper(), qt_strip_filters(), qt_win_extract_filter(), qt_win_filter(), read_xbm_header(), readSymLink(), QNSOpenSavePanelDelegate::removeExtensions:, QString::replace(), QDomDocumentPrivate::saveDocument(), QString::section(), QString::split(), and QScriptCompletionTask::start().

4137 {
4139  if (offset < 0)
4140  offset += str.length();
4141  priv->matchState.match(str.unicode(), str.length(), offset,
4142  priv->minimal, false, caretIndex(offset, caretMode));
4143  return priv->matchState.captured[0];
4144 }
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
static int caretIndex(int offset, QRegExp::CaretMode caretMode)
Definition: qregexp.cpp:858
const QChar * unicode() const
Returns a &#39;\0&#39;-terminated Unicode representation of the string.
Definition: qstring.h:706
QRegExpPrivate * priv
Definition: qregexp.h:153
static void prepareEngineForMatch(QRegExpPrivate *priv, const QString &str)
Definition: qregexp.cpp:3730
void match(const QChar *str, int len, int pos, bool minimal, bool oneTest, int caretIndex)
Definition: qregexp.cpp:1414

◆ isEmpty()

bool QRegExp::isEmpty ( ) const

Returns true if the pattern string is empty; otherwise returns false.

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 indexIn() with an empty pattern on any 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.

See QString::isEmpty().

Definition at line 3925 of file qregexp.cpp.

Referenced by QTextDocument::find().

3926 {
3927  return priv->engineKey.pattern.isEmpty();
3928 }
QString pattern
Definition: qregexp.cpp:874
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657

◆ isMinimal()

bool QRegExp::isMinimal ( ) const

Returns true if minimal (non-greedy) matching is enabled; otherwise returns false.

See also
caseSensitivity(), setMinimal()

Definition at line 4046 of file qregexp.cpp.

Referenced by QScriptEnginePrivate::newRegExp(), and operator<<().

4047 {
4048  return priv->minimal;
4049 }
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ isValid()

bool QRegExp::isValid ( ) const

Returns true if the regular expression is valid; otherwise returns false.

An invalid regular expression never matches.

The pattern [a-z is an example of an invalid pattern, since it lacks a closing square bracket.

Note that the validity of a regexp may also depend on the setting of the wildcard flag, for example *.html is a valid wildcard regexp but an invalid full regexp.

See also
errorString()

Definition at line 3943 of file qregexp.cpp.

Referenced by QPatternist::PatternPlatform::applyFlags(), QPatternist::AbstractDuration::CaptureTable::CaptureTable(), QPatternist::AbstractDateTime::CaptureTable::CaptureTable(), QPatternist::XsdSchemaChecker::checkConstrainingFacets(), QXmlUtils::isEncName(), ShaderEffectItem::lookThroughShaderCode(), QPatternist::PatternPlatform::parsePattern(), and QPatternist::PatternPlatform::pattern().

3944 {
3945  if (priv->engineKey.pattern.isEmpty()) {
3946  return true;
3947  } else {
3949  return priv->eng->isValid();
3950  }
3951 }
QString pattern
Definition: qregexp.cpp:874
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657
QRegExpEngine * eng
Definition: qregexp.cpp:3656
bool isValid() const
Definition: qregexp.cpp:1083

◆ lastIndexIn()

int QRegExp::lastIndexIn ( const QString str,
int  offset = -1,
CaretMode  caretMode = CaretAtZero 
) const

Attempts to find a match backwards in str from position offset.

If offset is -1 (the default), the search starts at the last character; if -2, at the next to last character; etc.

Returns the position of the first match, or -1 if there was no match.

The caretMode parameter can be used to instruct whether ^ should match at index 0 or at offset.

Although const, this function sets matchedLength(), capturedTexts() and pos().

Warning
Searching backwards is much slower than searching forwards.
See also
indexIn(), exactMatch()

Definition at line 4167 of file qregexp.cpp.

Referenced by findInBlock(), getDisplayId(), QAxServerBase::Invoke(), QString::lastIndexOf(), and qt_init().

4168 {
4170  if (offset < 0)
4171  offset += str.length();
4172  if (offset < 0 || offset > str.length()) {
4173  memset(priv->matchState.captured, -1, priv->matchState.capturedSize*sizeof(int));
4174  return -1;
4175  }
4176 
4177  while (offset >= 0) {
4178  priv->matchState.match(str.unicode(), str.length(), offset,
4179  priv->minimal, true, caretIndex(offset, caretMode));
4180  if (priv->matchState.captured[0] == offset)
4181  return offset;
4182  --offset;
4183  }
4184  return -1;
4185 }
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
static int caretIndex(int offset, QRegExp::CaretMode caretMode)
Definition: qregexp.cpp:858
const QChar * unicode() const
Returns a &#39;\0&#39;-terminated Unicode representation of the string.
Definition: qstring.h:706
QRegExpPrivate * priv
Definition: qregexp.h:153
static void prepareEngineForMatch(QRegExpPrivate *priv, const QString &str)
Definition: qregexp.cpp:3730
void match(const QChar *str, int len, int pos, bool minimal, bool oneTest, int caretIndex)
Definition: qregexp.cpp:1414

◆ matchedLength()

int QRegExp::matchedLength ( ) const

◆ numCaptures()

int QRegExp::numCaptures ( ) const

Returns the number of captures contained in the regular expression.

See also
captureCount()

Definition at line 4210 of file qregexp.cpp.

4211 {
4212  return captureCount();
4213 }
int captureCount() const
Returns the number of captures contained in the regular expression.
Definition: qregexp.cpp:4223

◆ operator!=()

bool QRegExp::operator!= ( const QRegExp rx) const
inline

Returns true if this regular expression is not equal to rx; otherwise returns false.

See also
operator==()

Definition at line 86 of file qregexp.h.

86 { return !operator==(rx); }
bool operator==(const QRegExp &rx) const
Returns true if this regular expression is equal to rx; otherwise returns false.
Definition: qregexp.cpp:3893

◆ operator=()

QRegExp & QRegExp::operator= ( const QRegExp rx)

Copies the regular expression rx and returns a reference to the copy.

The case sensitivity, wildcard, and minimal matching options are also copied.

Definition at line 3854 of file qregexp.cpp.

3855 {
3856  prepareEngine(rx.priv); // to allow sharing
3857  QRegExpEngine *otherEng = rx.priv->eng;
3858  if (otherEng)
3859  otherEng->ref.ref();
3861  priv->eng = otherEng;
3862  priv->engineKey = rx.priv->engineKey;
3863  priv->minimal = rx.priv->minimal;
3864 #ifndef QT_NO_REGEXP_CAPTURE
3865  priv->t = rx.priv->t;
3867 #endif
3868  if (priv->eng)
3871  return *this;
3872 }
QStringList capturedCache
Definition: qregexp.cpp:3661
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
bool ref()
Atomically increments the value of this QAtomicInt.
void prepareForMatch(QRegExpEngine *eng)
Definition: qregexp.cpp:1367
static void prepareEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3723
QAtomicInt ref
Definition: qregexp.cpp:1115
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657
QRegExpEngine * eng
Definition: qregexp.cpp:3656
static void invalidateEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3742

◆ operator==()

bool QRegExp::operator== ( const QRegExp rx) const

Returns true if this regular expression is equal to rx; otherwise returns false.

Two QRegExp objects are equal if they have the same pattern strings and the same settings for case sensitivity, wildcard and minimal matching.

Definition at line 3893 of file qregexp.cpp.

3894 {
3895  return priv->engineKey == rx.priv->engineKey && priv->minimal == rx.priv->minimal;
3896 }
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657

◆ pattern()

QString QRegExp::pattern ( ) const

Returns the pattern string of the regular expression.

The pattern has either regular expression syntax or wildcard syntax, depending on patternSyntax().

See also
patternSyntax(), caseSensitivity()

Definition at line 3960 of file qregexp.cpp.

Referenced by QScriptEnginePrivate::newRegExp(), operator<<(), and QPatternist::yyparse().

3961 {
3962  return priv->engineKey.pattern;
3963 }
QString pattern
Definition: qregexp.cpp:874
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657

◆ patternSyntax()

QRegExp::PatternSyntax QRegExp::patternSyntax ( ) const

Returns the syntax used by the regular expression.

The default is QRegExp::RegExp.

See also
pattern(), caseSensitivity()

Definition at line 4012 of file qregexp.cpp.

Referenced by QScriptEnginePrivate::newRegExp(), and operator<<().

4013 {
4014  return priv->engineKey.patternSyntax;
4015 }
QRegExp::PatternSyntax patternSyntax
Definition: qregexp.cpp:875
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657

◆ pos() [1/2]

int QRegExp::pos ( int  nth = 0) const

Returns the position of the nth captured text in the searched string.

If nth is 0 (the default), pos() returns the position of the whole match.

Example:

QRegExp rx("/([a-z]+)/([a-z]+)");
rx.indexIn("Output /dev/null"); // returns 7 (position of /dev/null)
rx.pos(0); // returns 7 (position of /dev/null)
rx.pos(1); // returns 8 (position of dev)
rx.pos(2); // returns 12 (position of null)

For zero-length matches, pos() always returns -1. (For example, if cap(4) would return an empty string, pos(4) returns -1.) This is a feature of the implementation.

See also
cap(), capturedTexts()

Definition at line 4337 of file qregexp.cpp.

Referenced by filterDisplayOffset(), filterTransformation(), QWSServerPrivate::newMouseHandler(), and QScriptCompletionTask::start().

4338 {
4339  if (nth < 0 || nth >= priv->matchState.capturedSize / 2)
4340  return -1;
4341  else
4342  return priv->matchState.captured[2 * nth];
4343 }
QRegExpMatchState matchState
Definition: qregexp.cpp:3663
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ pos() [2/2]

int QRegExp::pos ( int  nth = 0)
Warning
This function is not part of the public interface.

Definition at line 4348 of file qregexp.cpp.

4349 {
4350  return const_cast<const QRegExp *>(this)->pos(nth);
4351 }
The QRegExp class provides pattern matching using regular expressions.
Definition: qregexp.h:61
int pos(int nth=0) const
Returns the position of the nth captured text in the searched string.
Definition: qregexp.cpp:4337

◆ setCaseSensitivity()

void QRegExp::setCaseSensitivity ( Qt::CaseSensitivity  cs)

Sets case sensitive matching to cs.

If cs is Qt::CaseSensitive, \.txt$ matches readme.txt but not README.TXT.

See also
setPatternSyntax(), setPattern(), setMinimal()

Definition at line 3998 of file qregexp.cpp.

Referenced by QPatternist::PatternPlatform::applyFlags(), colorFromName(), QDirectFBScreen::connect(), QTextDocument::find(), QString::section(), and setIntOption().

3999 {
4000  if ((bool)cs != (bool)priv->engineKey.cs) {
4002  priv->engineKey.cs = cs;
4003  }
4004 }
Qt::CaseSensitivity cs
Definition: qregexp.cpp:876
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657
static void invalidateEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3742

◆ setMinimal()

void QRegExp::setMinimal ( bool  minimal)

Enables or disables minimal matching.

If minimal is false, matching is greedy (maximal) which is the default.

For example, suppose we have the input string "We must be <b>bold</b>, very <b>bold</b>!" and the pattern .*. With the default greedy (maximal) matching, the match is "We must be <span style="text-decoration: underline;"><b>bold</b>, very <b>bold</b></span>!". But with minimal (non-greedy) matching, the first match is: "We must be <span style="text-decoration: underline;"><b>bold</b></span>, very <b>bold</b>!" and the second match is "We must be <b>bold</b>, very <span style="text-decoration: underline;"><b>bold</b></span>!". In practice we might use the pattern [^<]*</b> instead, although this will still fail for nested tags.

See also
setCaseSensitivity()

Definition at line 4068 of file qregexp.cpp.

Referenced by QPSQLDriverPrivate::getPSQLVersion(), QLibraryInfo::location(), operator>>(), and QSvgHandler::processingInstruction().

4069 {
4070  priv->minimal = minimal;
4071 }
QRegExpPrivate * priv
Definition: qregexp.h:153

◆ setPattern()

void QRegExp::setPattern ( const QString pattern)

Sets the pattern string to pattern.

The case sensitivity, wildcard, and minimal matching options are not changed.

See also
setPatternSyntax(), setCaseSensitivity()

Definition at line 3971 of file qregexp.cpp.

3972 {
3973  if (priv->engineKey.pattern != pattern) {
3976  }
3977 }
QString pattern
Definition: qregexp.cpp:874
QString pattern() const
Returns the pattern string of the regular expression.
Definition: qregexp.cpp:3960
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657
static void invalidateEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3742

◆ setPatternSyntax()

void QRegExp::setPatternSyntax ( PatternSyntax  syntax)

Sets the syntax mode for the regular expression.

The default is QRegExp::RegExp.

Setting syntax to QRegExp::Wildcard enables simple shell-like wildcard matching. For example, r*.txt matches the string readme.txt in wildcard mode, but does not match readme.

Setting syntax to QRegExp::FixedString means that the pattern is interpreted as a plain string. Special characters (e.g., backslash) don't need to be escaped then.

See also
setPattern(), setCaseSensitivity(), escape()

Definition at line 4032 of file qregexp.cpp.

Referenced by QTextDocument::find().

4033 {
4034  if (syntax != priv->engineKey.patternSyntax) {
4036  priv->engineKey.patternSyntax = syntax;
4037  }
4038 }
QRegExp::PatternSyntax patternSyntax
Definition: qregexp.cpp:875
QRegExpPrivate * priv
Definition: qregexp.h:153
QRegExpEngineKey engineKey
Definition: qregexp.cpp:3657
static void invalidateEngine(QRegExpPrivate *priv)
Definition: qregexp.cpp:3742

◆ swap()

void QRegExp::swap ( QRegExp other)
inline

Swaps regular expression other with this regular expression.

Since
4.8

This operation is very fast and never fails.

Definition at line 83 of file qregexp.h.

83 { qSwap(priv, other.priv); }
void qSwap(T &value1, T &value2)
Definition: qglobal.h:2181
QRegExpPrivate * priv
Definition: qregexp.h:153

Friends and Related Functions

◆ operator<<()

QDataStream & operator<< ( QDataStream out,
const QRegExp regExp 
)
related

Writes the regular expression regExp to stream out.

See also
{Serializing Qt Data Types}

Definition at line 4521 of file qregexp.cpp.

4522 {
4523  return out << regExp.pattern() << (quint8)regExp.caseSensitivity()
4524  << (quint8)regExp.patternSyntax()
4525  << (quint8)!!regExp.isMinimal();
4526 }
unsigned char quint8
Definition: qglobal.h:934
Qt::CaseSensitivity caseSensitivity() const
Returns Qt::CaseSensitive if the regexp is matched case sensitively; otherwise returns Qt::CaseInsens...
Definition: qregexp.cpp:3985
QString pattern() const
Returns the pattern string of the regular expression.
Definition: qregexp.cpp:3960
PatternSyntax patternSyntax() const
Returns the syntax used by the regular expression.
Definition: qregexp.cpp:4012
bool isMinimal() const
Returns true if minimal (non-greedy) matching is enabled; otherwise returns false.
Definition: qregexp.cpp:4046

◆ operator>>()

QDataStream & operator>> ( QDataStream in,
QRegExp regExp 
)
related

Reads a regular expression from stream in into regExp.

See also
{Serializing Qt Data Types}

Definition at line 4538 of file qregexp.cpp.

4539 {
4540  QString pattern;
4541  quint8 cs;
4543  quint8 isMinimal;
4544 
4545  in >> pattern >> cs >> patternSyntax >> isMinimal;
4546 
4547  QRegExp newRegExp(pattern, Qt::CaseSensitivity(cs),
4548  QRegExp::PatternSyntax(patternSyntax));
4549 
4550  newRegExp.setMinimal(isMinimal);
4551  regExp = newRegExp;
4552  return in;
4553 }
The QRegExp class provides pattern matching using regular expressions.
Definition: qregexp.h:61
unsigned char quint8
Definition: qglobal.h:934
The QString class provides a Unicode character string.
Definition: qstring.h:83
CaseSensitivity
Definition: qnamespace.h:1451
QString pattern() const
Returns the pattern string of the regular expression.
Definition: qregexp.cpp:3960
PatternSyntax patternSyntax() const
Returns the syntax used by the regular expression.
Definition: qregexp.cpp:4012
PatternSyntax
The syntax used to interpret the meaning of the pattern.
Definition: qregexp.h:64
bool isMinimal() const
Returns true if minimal (non-greedy) matching is enabled; otherwise returns false.
Definition: qregexp.cpp:4046

Properties

◆ priv

QRegExpPrivate* QRegExp::priv
private

Definition at line 153 of file qregexp.h.

Referenced by operator=(), operator==(), and swap().


The documentation for this class was generated from the following files: