QRegExp(3qt)

πŸ“¦ version 3.3.8b, in fedora 43, fedora 44

🌸 QRegExp(3qt) 🌸

okay bestie, sit down, hydrate, because today we're reading QRegExp(3qt) together and it's genuinely iconic. This is the manpage for QRegExp, and I'm gonna walk you through every single crumb of it. no skipping. no skimming. we're doing this properly πŸ’…


πŸ“› NAME

QRegExp β€” pattern matching using regular expressions. that's it, that's the name, she's simple and she's powerful πŸŽ€


✨ SYNOPSIS ✨

First things first, the reentrancy tea: All the functions in this class are reentrant when Qt is built with thread support.</p> β€” and yes, that stray </p> is literally in the source, we don't ask questions πŸ’€

Include her like this:

#include <qregexp.h>

πŸ‘‘ Public Members πŸ‘‘

  • enum CaretMode { CaretAtZero, CaretAtOffset, CaretWontMatch } β€” three caret moods, pick your fighter
  • QRegExp () β€” no-arg constructor, she arrives with no thoughts, head empty 🫢
  • QRegExp ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE ) β€” the constructor that takes a pattern, with caseSensitive defaulting to TRUE and wildcard defaulting to FALSE
  • QRegExp ( const QRegExp & rx ) β€” copy constructor, twin energy
  • ~QRegExp () β€” destructor, she's leaving, say bye 😭
  • QRegExp & operator= ( const QRegExp & rx ) β€” assignment operator
  • bool operator== ( const QRegExp & rx ) const β€” are y'all the same?
  • bool operator!= ( const QRegExp & rx ) const β€” are y'all not the same?
  • bool isEmpty () const β€” vibe check: is she empty?
  • bool isValid () const β€” vibe check: is she valid?
  • QString pattern () const β€” hand over the pattern
  • void setPattern ( const QString & pattern ) β€” here, take a new pattern
  • bool caseSensitive () const β€” does she care about case?
  • void setCaseSensitive ( bool sensitive ) β€” make her care (or not)
  • bool wildcard () const β€” wildcard mode status
  • void setWildcard ( bool wildcard ) β€” toggle the wildcard
  • bool minimal () const β€” is she in her minimal era?
  • void setMinimal ( bool minimal ) β€” put her in her minimal era
  • bool exactMatch ( const QString & str ) const β€” exact match, no crumbs left behind
  • int match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const β€” and the original page flags this one as (obsolete), so noted, bestie ⚠️
  • int search ( const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero ) const β€” the search
  • int searchRev ( const QString & str, int offset = -1, CaretMode caretMode = CaretAtZero ) const β€” the reverse search, searching backwards like she's rereading the group chat
  • int matchedLength () const β€” how long was the match
  • int numCaptures () const β€” how many captures
  • QStringList capturedTexts () β€” all the captured texts, a whole collection
  • QString cap ( int nth = 0 ) β€” grab capture number nth, default 0
  • int pos ( int nth = 0 ) β€” position of capture nth, default 0
  • QString errorString () β€” what went wrong, in words

🌟 Static Public Members 🌟

  • QString escape ( const QString & str ) β€” static, so you don't even need an instance, she's self-sufficient

πŸ’– DESCRIPTION πŸ’–

The QRegExp class provides pattern matching using regular expressions. that's the whole assignment.

Regular expressions, or "regexps", are how you find patterns inside text, and that is useful in so many contexts, for example:

<center>.nf
</center>

(yes that's literally what's in the file, the pretty picture did not survive the conversion πŸ™ˆ)

So here's the plan, and I quote the vibe: we present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation itself. QRegExp is modeled on Perl's regexp language, and also fully supports Unicode. QRegExp can also be used in the weaker 'wildcard' (globbing) mode which works in a similar way to command shells. A good text on regexps is Mastering Regular Expressions: Powerful Techniques for Perl and Other Tools by Jeffrey E. Friedl, ISBN 1565922573. πŸ“š

Experienced regexp users may prefer to skip the introduction and go directly to the relevant information β€” no offense taken, iykyk.

In case of multi-threaded programming, note that QRegExp depends on QThreadStorage internally. For that reason, QRegExp should only be used with threads started with QThread, i.e. not with threads started with platform-specific APIs.

not me casually dropping a threading constraint in the middle of the intro πŸ’€ read it again, it matters.

Here's the tour, in order:

  • Introduction
  • Characters and Abbreviations for Sets of Characters
  • Sets of Characters
  • Quantifiers
  • Capturing Text
  • Assertions
  • Wildcard Matching (globbing)
  • Notes for Perl Users
  • Code Examples

πŸ¦‹ Introduction πŸ¦‹

Regexps are built up from expressions, quantifiers, and assertions. The simplest form of expression is simply a character, e.g. x or 5. An expression can also be a set of characters. For example, [ABCD] will match an A or a B or a C or a D. As a shorthand we could write this as [A-D]. If we want to match any of the captital letters in the English alphabet we can write [A-Z]. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. x{1,1} means match an x which occurs at least once and at most once. We'll look at assertions and more complex expressions later.

Note that in general regexps cannot be used to check for balanced brackets or tags. For example if you want to match an opening html <b> and its closing </b> you can only use a regexp if you know that these tags are not nested; the html fragment, <b>bold <b>bolder</b></b> will not match as expected. If you know the maximum level of nesting it is possible to create a regexp that will match correctly, but for an unknown level of nesting, regexps will fail.

this is the part everyone ignores and then everyone gets humbled by. nesting = regexp's villain origin story πŸ’€

We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with [0-9]{1,1} which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes [0-9]{1,2} meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits within a string. To ensure that we match against the whole string we must use the anchor assertions. We need ^ (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need $ (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is ^[0-9]{1,2}$. Note that assertions, such as ^ and $, do not match any characters.

If you've seen regexps elsewhere they may have looked different from the ones above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. [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. This means that x{1,1} is exactly the same as x alone. So our 0 to 99 matcher could be written ^\d{1,2}$. Another way of writing it would be ^\d\d{0,1}$, i.e. from the start of the string match a digit followed by zero or one digits. In practice most people would write it ^\d\d?$. The ? is a shorthand for the quantifier {0,1}, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp ^\d\d?$ means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string". πŸŽ€

Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, m{1,1}a{1,1}i{1,1}l{1,1}, but since each expression itself is automatically quantified by {1,1} we can simply write this as mail; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for alternation, so our regexp now becomes mail|letter|correspondence which means match 'mail' or 'letter' or 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parentheses, (mail|letter|correspondence). Parentheses have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to capture. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time \b "word boundary": \b(mail|letter|correspondence)\b. This regexp means "match a word boundary followed by the expression in parentheses followed by another word boundary". The \b assertion matches at a position in the regexp not a character in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string.

For our third example we want to replace ampersands with the HTML entity '&amp;'. The regexp to match is simple: &, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: &(?!amp;). The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must not follow the expression that preceeds it.

Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are \b(Eric|Eirik)\b and \bEi?ri[ck]\b. We need the word boundary '\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'.

We will implement some the examples above in the code examples section. ✨


🌈 Characters and Abbreviations for Sets of Characters 🌈

okay so the table in this manpage arrived completely mangled in transmission, and I refuse to pretend otherwise. here is literally every crumb of it, in the order it shows up, so nothing is lost:

Element
───────────────────────────────────────────────────────────────

regexp meaning. Thus

itself except where mentioned below. For example if you
wished to match a literal caret at the beginning of a string
you would write

hexadecimal number hhhh (between 0x0000 and 0xFFFF). \0ooo
(i.e., \zero ooo) matches the ASCII/Latin-1 character
corresponding to the octal number ooo (between 0 and 0377).

(and it's wrapped in <center>.nf … </center> tags, because of course it is πŸ™ˆ)

Note that the C++ compiler transforms backslashes in strings so to include a \ in a regexp you will need to enter it twice, i.e. \\.

this is the classic "why is my regexp not working" jump scare. the compiler ate your backslash, bestie. you have to feed it two πŸ“

🧚 Sets of Characters 🧚

Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets.

<center>.nf
</center>

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 that in most regexp literature sets of characters are called "character classes".

✨ Quantifiers ✨

Okay so by default every expression is automatically quantified by {1,1}, meaning it should occur exactly once. Periodt. In the list below, E stands for any expression β€” and an expression is a character, or an abbreviation for a set of characters, or a set of characters in square brackets, or any parenthesised expression. πŸ’…

ngl the table cells down here got absolutely eaten by the terminal, but here's everything that survived, untouched:
─────────────────────────────────────────────────────────────
means "the previous expression is optional" since it will
match whether or not the expression occurs in the string. It
is the same as

as

as

is the same as repeating the expression n times. For
example,

is the same as

is the same as

(MAXINT is implementation dependent but will not be smaller than 1024.)

So if we wanna apply a quantifier to more than just the one character right before it, we use parentheses to group characters together into an expression. For example, tag+ matches a 't' followed by an 'a' followed by at least one 'g' β€” but (tag)+ matches at least one occurrence of 'tag'. See the difference bestie? Grouping changes everything. 😭

Lowkey important: quantifiers are "greedy". They will match as much text as they possibly can. For example, 0+ will match as many zeros as it can from the first zero it finds, e.g. '2.0005'. And you can make quantifiers non-greedy β€” peep setMinimal(). 🫢


πŸŽ€ Capturing Text πŸŽ€

Parentheses let us group elements together so we can quantify them and capture them. Say we have the expression mail|letter|correspondence β€” it matches a string, sure, but we know one of those words matched and we have no idea which one. πŸ’€ Using parentheses lets us "capture" whatever matched inside their bounds, so if we used (mail|letter|correspondence) and matched that 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'. Iconic.

We can also use captured text inside the regexp itself. To refer back to captured text we use backreferences, which are indexed from 1, 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 parenthesised expression, followed by a word boundary. πŸ¦‹

And if we wanna use parentheses purely for grouping and not for capturing, we 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, 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. Main character energy: less work, same result.

Both capturing and non-capturing parentheses may be nested. ✨


πŸ‘‘ 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.

bestie the assertion table is literally empty in the source β€” not me losing details, there are simply none here to give you. 😭

🌈 Wildcard Matching (globbing) 🌈

Most command shells, like bash or cmd.exe, support "file globbing" β€” the ability to identify a group of files using wildcards. The setWildcard() function switches between regexp mode and wildcard mode. Wildcard matching is way simpler than full regexps and has only four features:

────────────
below. Thus

same as
again, the table got ate, so this is all that's left of it. 🫢

For example, if we're in wildcard mode and have strings containing filenames, we could identify HTML files with *.html. That'll match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'. Slay. πŸ“


πŸ’œ 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 you're using them for that purpose. In Perl the meaning of caret varies automagically depending on where it occurs, so escaping it is rarely necessary. Same energy applies to $, which in QRegExp always signifies the end of the string. πŸ’…

QRegExp's quantifiers are the same as Perl's greedy quantifiers. Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regexp ro+?m you need:

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

The equivalent of Perl's /i option is setCaseSensitive(FALSE).

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, 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 QStringList::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. Do not forget, bestie, or your regexp will simply not do the thing. πŸ’€

✨ Code Examples ✨

ok bestie, this is the part where it all clicks, I promise πŸ’–

QRegExp rx( "^\\d\\d?$" );  // match integers 0 to 99
rx.search( "123" );         // returns -1 (no match)
rx.search( "-6" );          // returns -1 (no match)
rx.search( "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. so cute, so efficient, we love her πŸŽ€

QRegExp rx( "^\\S+$" );     // match strings without whitespace
rx.search( "Hello world" ); // returns -1 (no match)
rx.search( "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. lowkey elegant πŸ’…

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.search( "I sent you an email" );     // returns -1 (no match)
rx.search( "Please write the letter" ); // returns 17

The second string matches "Please write the letter ". 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). fr fr, don't forget the 0 is the whole vibe 😌

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. chef's kiss, honestly πŸ‘‘

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.search( str, pos );
    if ( pos >= 0 ) {
        pos++;      // move along in str
        count++;    // count our Eric or Eirik
    }
}

We've used the search() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time 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. the boundaries are doing the heavy lifting and they ATE πŸ”₯

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

str = "Trolltech AS\twww.trolltech.com\tNorway";
QString company, web, country;
rx.setPattern( "^([^\t]+)\t([^\t]+)\t([^\t]+)$" );
if ( rx.search( 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 QStringList split() function can take a separator string or regexp as an argument and split a string accordingly.

QStringList field = QStringList::split( "\t", str );

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

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

QRegExp rx( "*.html" );         // invalid regexp: * doesn't quantify anything
rx.setWildcard( TRUE );         // now it's a valid wildcard regexp
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?$. πŸ’€ yeah that *.htm* is giving chaos energy, avoid

QRegExp can match case insensitively using setCaseSensitive(), 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 search() or backward with searchRev(). Captured text can be accessed using capturedTexts() which returns a string list of all captured strings, or using cap() which returns the captured string for the given index. The pos() function takes a match index and returns the position in the string where the match was made (or -1 if there was no match).

See also QRegExpValidator, QString, QStringList, Miscellaneous Classes, Implicitly and Explicitly Shared Classes, and Non-GUI Classes.


🧁 Member Type Documentation 🧁

QRegExp::CaretMode

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

  • QRegExp::CaretAtZero β€” The caret corresponds to index 0 in the searched string.
  • QRegExp::CaretAtOffset β€” The caret corresponds to the start offset of the search.
  • QRegExp::CaretWontMatch β€” The caret never matches.

three moods, pick your fighter 🫢


πŸ’– MEMBER FUNCTION DOCUMENTATION πŸ’–

QRegExp::QRegExp ()

Constructs an empty regexp.

See also isValid() and errorString().

QRegExp::QRegExp ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE )

Constructs a regular expression object for the given pattern string. The pattern must be given using wildcard notation if wildcard is TRUE (default is FALSE). The pattern is case sensitive, unless caseSensitive is FALSE. Matching is greedy (maximal), but can be changed by calling setMinimal().

See also setPattern(), setCaseSensitive(), setWildcard(), and setMinimal().

QRegExp::QRegExp ( const QRegExp & rx )

Constructs a regular expression as a copy of rx.

See also operator=().

QRegExp::~QRegExp ()

Destroys the regular expression and cleans up its internal data. rest in peace queen, your internal data is safe with us 😭

QString QRegExp::cap ( int nth = 0 )

Returns the text captured by the nth subexpression. The entire match has index 0 and the parenthesized subexpressions have indices starting from 1 (excluding non-capturing parentheses).

QRegExp rxlen( "(\\d+)(?:\\s*)(cm|inch)" );
int pos = rxlen.search( "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.

Some patterns may lead to a number of matches which cannot be determined in advance, for example:

QRegExp rx( "(\\d+)" );
str = "Offsets: 12 14 99 231 7";
QStringList list;
pos = 0;
while ( pos >= 0 ) {
    pos = rx.search( str, pos );
    if ( pos > -1 ) {
        list += rx.cap( 1 );
        pos  += rx.matchedLength();
    }
}
// list contains "12", "14", "99", "231", "7"

See also capturedTexts(), pos(), exactMatch(), search(), and searchRev().

Examples:

QStringList QRegExp::capturedTexts ()

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.search( "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.search( "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 calling rx.search(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. > ngl bestie, that's a little bit of a jumpscare β€” loop with cap() and you're fine πŸ™ˆ

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(), exactMatch(), search(), and searchRev().

bool QRegExp::caseSensitive () const

Returns TRUE if case sensitivity is enabled; otherwise returns FALSE. The default is TRUE.

See also setCaseSensitive().

QString QRegExp::errorString ()

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

See also isValid().

Example: regexptester/regexptester.cpp.

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

Returns the string str with every regexp special character escaped with a backslash. The special characters are $, (, ), *, +,

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) + ")" );
  • bool QRegExp::exactMatch ( const QString & str ) const β€” bestie this one is picky on purpose πŸ’… It returns TRUE only if str is matched exactly by this regex; otherwise FALSE. And if you wanna know how much of the string actually got matched, just call matchedLength().

For any given regexp string R, exactMatch("R") is literally the same energy as search("^R$"), because exactMatch() wraps the regexp up in the start-of-string and end-of-string anchors β€” except it sets matchedLength() differently. so don't @ me.

Say your regex is blue. Then exactMatch() returns TRUE for input blue and only blue. For inputs bluebell, blutak and lightblue, exactMatch() returns FALSE, and matchedLength() will hand you 4, 3 and 0 respectively. iconic behavior honestly.

Even though it's const, this function sets matchedLength(), capturedTexts() and pos(). yes, really. it's giving sneaky.

See also search(), searchRev(), and QRegExpValidator.

  • bool QRegExp::isEmpty () const β€” Returns TRUE if the pattern string is empty; otherwise FALSE. 🫢

Okay so the lore here: if you call exactMatch() with an empty pattern on an empty string, it returns TRUE. Otherwise it returns FALSE, because it operates over the whole string. But if you call search() with an empty pattern on any string, it returns the start offset (0 by default), because the empty pattern matches the 'emptiness' at the start of the string. In that case the length of the match returned by matchedLength() will be 0. ✨

See also QString::isEmpty().

  • bool QRegExp::isValid () const β€” Returns TRUE if the regular expression is valid; otherwise FALSE. An invalid regular expression never matches. no cap, never. πŸ’€

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

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. vibe check accordingly.

See also errorString().

Example: regexptester/regexptester.cpp.

  • int QRegExp::match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const β€” 🚨 This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. it's giving 2007 tumblr era, we don't do that anymore.

It attempts to match in str, starting from position index. Returns the position of the match, or -1 if there was no match.

The length of the match is stored in *len, unless len is a null pointer.

If indexIsStart is TRUE (the default), the position index in the string will match the start of string anchor, ^, in the regexp, if present. Otherwise, position 0 in str will match.

Use search() and matchedLength() instead of this function. periodt.

See also QString::mid() and QConstString.

Example: qmag/qmag.cpp.

  • int QRegExp::matchedLength () const β€” Returns the length of the last matched string, or -1 if there was no match. 🌸

See also exactMatch(), search(), and searchRev().

Examples:

  • bool QRegExp::minimal () const β€” Returns TRUE if minimal (non-greedy) matching is enabled; otherwise returns FALSE.

See also setMinimal().

  • int QRegExp::numCaptures () const β€” Returns the number of captures contained in the regular expression. counting your girlies fr fr πŸŽ€

Example: regexptester/regexptester.cpp.

  • bool QRegExp::operator!= ( const QRegExp & rx ) const β€” Returns TRUE if this regular expression is not equal to rx; otherwise returns FALSE.

See also 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. so it's a full clone, not a glow-up. πŸ’œ
  • 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. all three, bestie. no shortcuts. βœ…

  • QString QRegExp::pattern () const β€” Returns the pattern string of the regular expression. The pattern has either regular expression syntax or wildcard syntax, depending on wildcard(). πŸ¦‹

See also setPattern().

  • int QRegExp::pos ( int nth = 0 ) β€” 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.search( "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 due to an implementation tradeoff. 😭 we don't make the rules.

See also capturedTexts(), exactMatch(), search(), and searchRev().

  • int QRegExp::search ( 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. yes, negative offsets go backwards from the end, we love a flexible queen. πŸ‘‘

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::find(), QString::contains() or even QStringList::grep(). 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.search(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(). same sneaky energy as before, iykyk πŸ™ˆ

See also searchRev() and exactMatch().

Examples:

  • int QRegExp::searchRev ( 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. πŸ’€ it's giving walking up the stairs in heels. worth it sometimes but you WILL feel it.

See also search() and exactMatch().

  • void QRegExp::setCaseSensitive ( bool sensitive ) β€” Sets case sensitive matching to sensitive.

If sensitive is TRUE, \.txt$ matches readme.txt but not README.TXT. lowercase girlies only πŸ’…

See also caseSensitive().

Example: regexptester/regexptester.cpp.

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

See also minimal().

Examples:

  • void QRegExp::setPattern ( const QString & pattern ) β€” Sets the pattern string to pattern. The case sensitivity, wildcard and minimal matching options are not changed. so swap the pattern, keep the settings. πŸŽ€

See also pattern().

  • void QRegExp::setWildcard ( bool wildcard ) β€” Sets the wildcard mode for the regular expression. The default is FALSE.

Setting wildcard to TRUE enables simple shell-like wildcard matching. (See wildcard matching (globbing).)

For example, r*.txt matches the string readme.txt in wildcard mode, but does not match readme.

See also wildcard().

Example: regexptester/regexptester.cpp.

  • bool QRegExp::wildcard () const β€” Returns TRUE if wildcard mode is enabled; otherwise returns FALSE. The default is FALSE.

See also setWildcard().


🌟 SEE ALSO 🌟

http://doc.trolltech.com/qregexp.html http://www.trolltech.com/faq/tech.html


Copyright 1992-2007 Trolltech ASA, http://www.trolltech.com. See the license file included in the distribution for a complete license statement.


✍️ AUTHOR ✍️

Generated automatically from the source code.


πŸ› BUGS πŸ›

If you find a bug in Qt, please report it as described in http://doc.trolltech.com/bughowto.html. Good bug reports help us to help you. Thank you. 🫢

The definitive Qt documentation is provided in HTML format; it is located at $QTDIR/doc/html and can be read using Qt Assistant or with a web browser. This man page is provided as a convenience for those users who prefer man pages, although this format is not officially supported by Trolltech.

If you find errors in this manual page, please report them to qt-bugs@trolltech.com. Please include the name of the manual page (qregexp.3qt) and the Qt version (3.3.8).


okay bestie that's the whole page, we did it πŸ’– this came from Trolltech AS, dated 2 February 2007, for QRegExp(3qt) β€” go forth and match some strings, you're the main character now πŸ‘‘βœ¨

πŸ“¦ where this page comes from