⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qregexp.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 5 页
字号:
    \target capturing parentheses    \target backreferences    \section1 Capturing Text    Parentheses allow us to group elements together so that we can    quantify and capture them. For example if we have the expression    \bold{mail|letter|correspondence} that matches a string we know    that \e 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 \bold{(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 \e backreferences which are indexed from 1,    the same as for cap(). For example we could search for duplicate    words in a string using \bold{\\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.    \bold{(?: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.    \target greedy quantifiers    For historical reasons, quantifiers (e.g. \bold{*}) that apply to    capturing parentheses are more "greedy" than other quantifiers.    For example, \bold{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).    \target cap_in_a_loop    When the number of matches cannot be determined in advance, a    common idiom is to use cap() in a loop. For example:    \code        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"]    \endcode    \target assertions    \section1 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 \bold{\e {E}} stands for any expression.    \table    \row \i \bold{^}         \i The caret signifies the beginning of the string. If you         wish to match a literal \c{^} you must escape it by         writing \c{\\^}. For example, \bold{^#include} will only         match strings which \e begin with the characters '#include'.         (When the caret is the first character of a character set it         has a special meaning, see \link #sets-of-characters Sets of         Characters \endlink.)    \row \i \bold{$}         \i The dollar signifies the end of the string. For example         \bold{\\d\\s*$} will match strings which end with a digit         optionally followed by whitespace. If you wish to match a         literal \c{$} you must escape it by writing         \c{\\$}.    \row \i \bold{\\b}         \i A word boundary. For example the regexp         \bold{\\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 \bold{(\\bOK\\b)} and we have a match it will only         contain 'OK' even if the string is "It's \underline{OK} now".    \row \i \bold{\\B}         \i A non-word boundary. This assertion is true wherever         \bold{\\b} is false. For example if we searched for         \bold{\\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\underline{on}ne".    \row \i \bold{(?=\e E)}         \i Positive lookahead. This assertion is true if the         expression matches at this point in the regexp. For example,         \bold{const(?=\\s+char)} matches 'const' whenever it is         followed by 'char', as in 'static \underline{const} char *'.         (Compare with \bold{const\\s+char}, which matches 'static         \underline{const char} *'.)    \row \i \bold{(?!\e E)}         \i Negative lookahead. This assertion is true if the         expression does not match at this point in the regexp. For         example, \bold{const(?!\\s+char)} matches 'const' \e except         when it is followed by 'char'.    \endtable    \keyword QRegExp wildcard matching    \section1 Wildcard Matching    Most command shells such as \e bash or \e 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:    \table    \row \i \bold{c}         \i Any character represents itself apart from those mentioned         below. Thus \bold{c} matches the character \e c.    \row \i \bold{?}         \i This matches any single character. It is the same as         \bold{.} in full regexps.    \row \i \bold{*}         \i This matches zero or more of any characters. It is the         same as \bold{.*} in full regexps.    \row \i \bold{[...]}         \i Sets of characters can be represented in square brackets,         similar to full regexps. Within the character class, like         outside, backslash has no special meaning.    \endtable    For example if we are in wildcard mode and have strings which    contain filenames we could identify HTML files with \bold{*.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:    \code        QRegExp rx("*.txt");        rx.setPatternSyntax(QRegExp::Wildcard);        rx.exactMatch("README.txt");        // returns true        rx.exactMatch("welcome.txt.bak");   // returns false    \endcode    \target perl-users    \section1 Notes for Perl Users    Most of the character class abbreviations supported by Perl are    supported by QRegExp, see \link    #characters-and-abbreviations-for-sets-of-characters characters    and abbreviations for sets of characters \endlink.    In QRegExp, apart from within character classes, \c{^} 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 \c{$} which in    QRegExp always signifies the end of the string.    QRegExp's quantifiers are the same as Perl's greedy quantifiers    (but see the \l{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 \bold{ro+?m} requires: \code QRegExp    rx("ro+m"); rx.setMinimal(true); \endcode    The equivalent of Perl's \c{/i} option is    setCaseSensitivity(Qt::CaseInsensitive).    Perl's \c{/g} option can be emulated using a \l{#cap_in_a_loop}{loop}.    In QRegExp \bold{.} matches any character, therefore all QRegExp    regexps have the equivalent of Perl's \c{/s} option. QRegExp    does not have an equivalent to Perl's \c{/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 \c{/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:    \code        QRegExp mark("\\b"      // word boundary                      "[Mm]ark" // the word we want to match                    );    \endcode    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 \e twice in    code, e.g. \bold{\\b} must be written \bold{\\\\b}.    \target code-examples    \section1 Code Examples    \code        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)    \endcode    The third string matches '\underline{6}'. This is a simple validation    regexp for integers in the range 0 to 99.    \code        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)    \endcode    The second string matches '\underline{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'    \code        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    \endcode    The second string matches "Please write the \underline{letter}". The    word 'letter' is also captured (because of the parentheses). We    can see what text we've captured like this:    \code        QString captured = rx.cap(1); // captured == "letter"    \endcode    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).    \code        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"    \endcode    Here we've passed the QRegExp to QString's replace() function to    replace the matched text with new text.    \code        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            }        }    \endcode    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 \c pos++ we could have written \c {pos +=    rx.matchedLength()} to skip over the already matched string. The    count will equal 3, matching 'One \underline{Eric} another    \underline{Eirik}, and an Ericsson. How many Eiriks, \underline{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.    \code        str = "Trolltech ASA\twww.trolltech.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);        }    \endcode    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.    \code        QStringList field = str.split("\t");    \endcode    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.    \code        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    \endcode    Wildcard matching can be convenient because of its simplicity, but    any wildcard regexp can be defined using full regexps, e.g.    \bold{.*\.html$}. Notice that we can't match both \c .html and \c    .htm files with a wildcard unless we use \bold{*.htm*} which will    also match 'test.html.bak'. A full regexp gives us the precision    we need, \bold{.*\\.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).    \sa QString, QStringList, QRegExpValidator, QSortFilterProxyModel,        {tools/regexp}{Regular Expression Example}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -