Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QRegExp Class

TheQRegExp class provides pattern matching using regular expressions.More...

Header:#include <QRegExp>

Note: All functions in this class arereentrant.

Public Types

enumCaretMode { CaretAtZero, CaretAtOffset, CaretWontMatch }
enumPatternSyntax { RegExp, RegExp2, Wildcard, WildcardUnix, FixedString, W3CXmlSchema11 }

Public Functions

QRegExp()
QRegExp(const QString & pattern, Qt::CaseSensitivity cs = Qt::CaseSensitive, PatternSyntax syntax = RegExp)
QRegExp(const QRegExp & rx)
~QRegExp()
QStringcap(int nth = 0) const
intcaptureCount() const
QStringListcapturedTexts() const
Qt::CaseSensitivitycaseSensitivity() const
QStringerrorString() const
boolexactMatch(const QString & str) const
intindexIn(const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero) const
boolisEmpty() const
boolisMinimal() const
boolisValid() const
intlastIndexIn(const QString & str, int offset = -1, CaretMode caretMode = CaretAtZero) const
intmatchedLength() const
QStringpattern() const
PatternSyntaxpatternSyntax() const
intpos(int nth = 0) const
voidsetCaseSensitivity(Qt::CaseSensitivity cs)
voidsetMinimal(bool minimal)
voidsetPattern(const QString & pattern)
voidsetPatternSyntax(PatternSyntax syntax)
voidswap(QRegExp & other)
booloperator!=(const QRegExp & rx) const
QRegExp &operator=(const QRegExp & rx)
QRegExp &operator=(QRegExp && other)
booloperator==(const QRegExp & rx) const

Static Public Members

QStringescape(const QString & str)

Related Non-Members

QDataStream &operator<<(QDataStream & out, const QRegExp & regExp)
QDataStream &operator>>(QDataStream & in, QRegExp & regExp)

Detailed Description

TheQRegExp class provides pattern matching using regular expressions.

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

ValidationA regexp can test whether a substring meets some criteria, e.g. is an integer or contains no whitespace.
SearchingA regexp provides more powerful pattern matching than simple substring matching, e.g., match one of the wordsmail,letter orcorrespondence, but none of the wordsemail,mailman,mailer,letterbox, etc.
Search and ReplaceA 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 anamp;.
String SplittingA 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 byQRegExp can be changed withsetPatternSyntax(). In particular, the pattern syntax can be set toQRegExp::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 isMastering 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 or5. An expression can also be a set of characters enclosed in square brackets.[ABCD] will match anA or aB or aC or aD. 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 onex.x{1,5} means match a sequence ofx characters that contains at least onex 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<b> and its closing</b>, if the<b> tags are not nested, but if the<b> tags are nested, that same regexp will match an opening<b> tag with the wrong closing</b>. For the fragment<b>bold <b>bolder</b></b>, the first<b> would be matched with the first</b>, 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 asx. 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?$ meansFrom 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 ism{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 tomail, i.e., an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. Now we can use the vertical bar|, which meansor, to include the other two words, so our regexp for matching any of the three words becomesmail|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 tocapture. 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\bword 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 aposition in the regexp, not acharacter. 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 byamp;. For this, we need the negative lookahead assertion,(?!__). The regexp can then be written as&(?!amp;), i.e.Match an ampersand that isnotfollowed byamp;.

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 thecode examples section.

Characters and Abbreviations for Sets of Characters

ElementMeaning
cA character represents itself unless it has a special regexp meaning. e.g.c matches the characterc.
\cA 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\^.
\aMatches the ASCII bell (BEL, 0x07).
\fMatches the ASCII form feed (FF, 0x0C).
\nMatches the ASCII line feed (LF, 0x0A, Unix newline).
\rMatches the ASCII carriage return (CR, 0x0D).
\tMatches the ASCII horizontal tab (HT, 0x09).
\vMatches the ASCII vertical tab (VT, 0x0B).
\xhhhhMatches the Unicode character corresponding to the hexadecimal numberhhhh (between 0x0000 and 0xFFFF).
\0ooo (i.e., \zeroooo)matches the ASCII/Latin1 character for the octal numberooo (between 0 and 0377).
. (dot)Matches any character (including newline).
\dMatches a digit (QChar::isDigit()).
\DMatches a non-digit.
\sMatches a whitespace character (QChar::isSpace()).
\SMatches a non-whitespace character.
\wMatches a word character (QChar::isLetterOrNumber(),QChar::isMark(), or '_').
\WMatches a non-word character.
\nThen-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.

^The caret negates the character set if it occurs as the first character (i.e. immediately after the opening square bracket).[abc] matches 'a' or 'b' or 'c', but[^abc] matches anythingbut 'a' or 'b' or 'c'.
-The dash indicates a range of characters.[W-Z] 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 inany 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?Matches zero or one occurrences ofE. This quantifier meansThe previous expression is optional, because it will match whether or not the expression is found.E? is the same asE{0,1}. e.g.,dents? matches 'dent' or 'dents'.
E+Matches one or more occurrences ofE.E+ is the same asE{1,}. e.g.,0+ matches '0', '00', '000', etc.
E*Matches zero or more occurrences ofE. It is the same asE{0,}. The* quantifier is often used in error where+ should be used. For example, if\s*$ is used in an expression to match strings that end in whitespace, it will match every string because\s*$ meansMatch zero or more whitespaces followed by end of string. The correct regexp to match strings that have at least one trailing whitespace character is\s+$.
E{n}Matches exactlyn occurrences ofE.E{n} is the same as repeatingEn times. For example,x{5} is the same asxxxxx. It is also the same asE{n,n}, e.g.x{5,5}.
E{n,}Matches at leastn occurrences ofE.
E{,m}Matches at mostm occurrences ofE.E{,m} is the same asE{0,m}.
E{n,m}Matches at leastn and at mostm occurrences ofE.

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, seesetMinimal().

Capturing Text

Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expressionmail|letter|correspondence that matches a string we know thatone 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 thecap() orcapturedTexts() 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 usebackreferences which are indexed from 1, the same as forcap(). 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, specifyQRegExp::RegExp2 to theQRegExp constructor or callsetPatternSyntax(QRegExp::RegExp2).

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

QRegExp rx("(\\d+)");QString str="Offsets: 12 14 99 231 7";QStringList list;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 listE 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 whichbegin with the characters '#include'. (When the caret is the first character of a character set it has a special meaning, seeSets 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\\$.
\bA 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'sOK now".
\BA 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 "tonne".
(?=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 'staticconst char *'. (Compare withconst\s+char, which matches 'staticconst 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'.

Wildcard Matching

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

cAny character represents itself apart from those mentioned below. Thusc matches the characterc.
?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 modeWildcardUnix, 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, useexactMatch(). For example:

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

Notes for Perl Users

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

InQRegExp, 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 inQRegExp always signifies the end of the string.

QRegExp's quantifiers are the same as Perl's greedy quantifiers (but see thenote 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 regexpro+?m requires:

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

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

Perl's/g option can be emulated using aloop.

InQRegExp. matches any character, therefore allQRegExp 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.

BecauseQRegExp 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) orcapturedTexts()[0]. There are noQRegExp equivalents for $`, $' or $+. Perl's capturing variables, $1, $2, ... correspond to cap(1) orcapturedTexts()[1], cap(2) orcapturedTexts()[2], etc.

To substitute a pattern useQString::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.

SeeQString::split() andQStringList::join() for equivalents to Perl's split and join functions.

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

Code Examples

QRegExp rx("^\\d\\d?$");// match integers 0 to 99rx.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 whitespacerx.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 theletter". 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 theQRegExp toQString'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 Eirikint pos=0;// where we are in the stringint count=0;// how many Eric and Eirik's we've countedwhile (pos>=0) {    pos= rx.indexIn(str, pos);if (pos>=0) {++pos;// move along in str++count;// count our Eric or Eirik    }}

We've used theindexIn() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a timepos++ we could have writtenpos += rx.matchedLength() to skip over the already matched string. The count will equal 3, matching 'OneEric anotherEirik, 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. TheQString::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 truerx.exactMatch("default.htm");// returns falserx.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 usingsetCaseSensitivity(), and can use non-greedy matching, seesetMinimal(). By defaultQRegExp uses full regexps but this can be changed withsetWildcard(). Searching can be forward withindexIn() or backward withlastIndexIn(). Captured text can be accessed usingcapturedTexts() which returns a string list of all captured strings, or usingcap() which returns the captured string for the given index. Thepos() 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 alsoQString,QStringList,QRegExpValidator,QSortFilterProxyModel, andRegular Expression Example.

Member Type Documentation

enum QRegExp::CaretMode

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

ConstantValueDescription
QRegExp::CaretAtZero0The caret corresponds to index 0 in the searched string.
QRegExp::CaretAtOffset1The caret corresponds to the start offset of the search.
QRegExp::CaretWontMatch2The caret never matches.

enum QRegExp::PatternSyntax

The syntax used to interpret the meaning of the pattern.

ConstantValueDescription
QRegExp::RegExp0A rich Perl-like pattern matching syntax. This is the default.
QRegExp::RegExp23Like RegExp, but withgreedy quantifiers. This will be the default in Qt 5. (Introduced in Qt 4.2.)
QRegExp::Wildcard1This provides a simple pattern matching syntax similar to that used by shells (command interpreters) for "file globbing". SeeWildcard Matching.
QRegExp::WildcardUnix4This is similar to Wildcard but with the behavior of a Unix shell. The wildcard characters can be escaped with the character "\".
QRegExp::FixedString2The pattern is a fixed string. This is equivalent to using the RegExp pattern on a string in which all metacharacters are escaped usingescape().
QRegExp::W3CXmlSchema115The pattern is a regular expression as defined by the W3C XML Schema 1.1 specification.

See alsosetPatternSyntax().

Member Function Documentation

QRegExp::QRegExp()

Constructs an empty regexp.

See alsoisValid() anderrorString().

QRegExp::QRegExp(constQString & pattern,Qt::CaseSensitivity cs = Qt::CaseSensitive,PatternSyntax syntax = RegExp)

Constructs a regular expression object for the givenpattern string. The pattern must be given using wildcard notation ifsyntax isWildcard; the default isRegExp. The pattern is case sensitive, unlesscs isQt::CaseInsensitive. Matching is greedy (maximal), but can be changed by callingsetMinimal().

See alsosetPattern(),setCaseSensitivity(), andsetPatternSyntax().

QRegExp::QRegExp(constQRegExp & rx)

Constructs a regular expression as a copy ofrx.

See alsooperator=().

QRegExp::~QRegExp()

Destroys the regular expression and cleans up its internal data.

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

Returns the text captured by thenth 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 alsocapturedTexts() andpos().

int QRegExp::captureCount() const

Returns the number of captures contained in the regular expression.

This function was introduced in Qt 4.6.

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();QStringList::iterator it= list.begin();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 callingrx.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 usecap() in aloop.

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 alsocap() andpos().

Qt::CaseSensitivity QRegExp::caseSensitivity() const

ReturnsQt::CaseSensitive if the regexp is matched case sensitively; otherwise returnsQt::CaseInsensitive.

See alsosetCaseSensitivity(),patternSyntax(),pattern(), andisMinimal().

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

[static]QString QRegExp::escape(constQString & str)

Returns the stringstr 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 rx("("+QRegExp::escape(name)+"|"+QRegExp::escape(alias)+")");

See alsosetPatternSyntax().

bool QRegExp::exactMatch(constQString & str) const

Returns true ifstr is matched exactly by this regular expression; otherwise returns false. You can determine how much of the string was matched by callingmatchedLength().

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

For example, if the regular expression isblue, then exactMatch() returns true only for inputblue. For inputsbluebell,blutak andlightblue, exactMatch() returns false andmatchedLength() will return 4, 3 and 0 respectively.

Although const, this function setsmatchedLength(),capturedTexts(), andpos().

See alsoindexIn() andlastIndexIn().

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

Attempts to find a match instr from positionoffset (0 by default). Ifoffset 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.

ThecaretMode parameter can be used to instruct whether^ should match at index 0 or atoffset.

You might prefer to useQString::indexOf(),QString::contains(), or evenQStringList::filter(). To replace matches useQString::replace().

Example:

QString str="offsets: 1.23 .50 71.00 6.00";QRegExp rx("\\d*\\.\\d+");// primitive floating point matchingint 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 setsmatchedLength(),capturedTexts() andpos().

If theQRegExp is a wildcard expression (seesetPatternSyntax()) and want to test a string against the whole wildcard expression, useexactMatch() instead of this function.

See alsolastIndexIn() andexactMatch().

bool QRegExp::isEmpty() const

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

If you callexactMatch() 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 callindexIn() with an empty pattern onany 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 bymatchedLength() will be 0.

SeeQString::isEmpty().

bool QRegExp::isMinimal() const

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

See alsocaseSensitivity() andsetMinimal().

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

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

Attempts to find a match backwards instr from positionoffset. Ifoffset 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.

ThecaretMode parameter can be used to instruct whether^ should match at index 0 or atoffset.

Although const, this function setsmatchedLength(),capturedTexts() andpos().

Warning: Searching backwards is much slower than searching forwards.

See alsoindexIn() andexactMatch().

int QRegExp::matchedLength() const

Returns the length of the last matched string, or -1 if there was no match.

See alsoexactMatch(),indexIn(), andlastIndexIn().

QString QRegExp::pattern() const

Returns the pattern string of the regular expression. The pattern has either regular expression syntax or wildcard syntax, depending onpatternSyntax().

See alsosetPattern(),patternSyntax(), andcaseSensitivity().

PatternSyntax QRegExp::patternSyntax() const

Returns the syntax used by the regular expression. The default isQRegExp::RegExp.

See alsosetPatternSyntax(),pattern(), andcaseSensitivity().

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

Returns the position of thenth captured text in the searched string. Ifnth 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 alsocap() andcapturedTexts().

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

Sets case sensitive matching tocs.

Ifcs isQt::CaseSensitive,\.txt$ matchesreadme.txt but notREADME.TXT.

See alsocaseSensitivity(),setPatternSyntax(),setPattern(), andsetMinimal().

void QRegExp::setMinimal(bool minimal)

Enables or disables minimal matching. Ifminimal 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<b>.*</b>. With the default greedy (maximal) matching, the match is "We must be<b>bold</b>, very <b>bold</b>!". But with minimal (non-greedy) matching, the first match is: "We must be<b>bold</b>, very <b>bold</b>!" and the second match is "We must be <b>bold</b>, very<b>bold</b>!". In practice we might use the pattern<b>[^<]*</b> instead, although this will still fail for nested tags.

See alsominimal() andsetCaseSensitivity().

void QRegExp::setPattern(constQString & pattern)

Sets the pattern string topattern. The case sensitivity, wildcard, and minimal matching options are not changed.

See alsopattern(),setPatternSyntax(), andsetCaseSensitivity().

void QRegExp::setPatternSyntax(PatternSyntax syntax)

Sets the syntax mode for the regular expression. The default isQRegExp::RegExp.

Settingsyntax toQRegExp::Wildcard enables simple shell-likewildcard matching. For example,r*.txt matches the stringreadme.txt in wildcard mode, but does not matchreadme.

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

See alsopatternSyntax(),setPattern(),setCaseSensitivity(), andescape().

void QRegExp::swap(QRegExp & other)

Swaps regular expressionother with this regular expression. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

bool QRegExp::operator!=(constQRegExp & rx) const

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

See alsooperator==().

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

Copies the regular expressionrx and returns a reference to the copy. The case sensitivity, wildcard, and minimal matching options are also copied.

QRegExp & QRegExp::operator=(QRegExp && other)

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

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

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

Related Non-Members

QDataStream &operator<<(QDataStream & out, constQRegExp & regExp)

Writes the regular expressionregExp to streamout.

See alsoSerializing Qt Data Types.

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

Reads a regular expression from streamin intoregExp.

See alsoSerializing Qt Data Types.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp