QRegularExpression Class
The QRegularExpression class provides pattern matching using regular expressions. More...
| Header: | #include <QRegularExpression> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Core)target_link_libraries(mytarget PRIVATE Qt6::Core) |
| qmake: | QT += core |
- List of all members, including inherited members
- Deprecated members
- QRegularExpression is part of Implicitly Shared Classes and Classes for string data.
This class is equality-comparable.
Note: All functions in this class are reentrant.
Public Types
| enum | MatchOption { NoMatchOption, AnchoredMatchOption, AnchorAtOffsetMatchOption, DontCheckSubjectStringMatchOption } |
| flags | MatchOptions |
| enum | MatchType { NormalMatch, PartialPreferCompleteMatch, PartialPreferFirstMatch, NoMatch } |
| enum | PatternOption { NoPatternOption, CaseInsensitiveOption, DotMatchesEverythingOption, MultilineOption, ExtendedPatternSyntaxOption, …, UseUnicodePropertiesOption } |
| flags | PatternOptions |
(since 6.0) enum | WildcardConversionOption { DefaultWildcardConversion, UnanchoredWildcardConversion, NonPathWildcardConversion } |
| flags | WildcardConversionOptions |
Public Functions
| QRegularExpression() | |
| QRegularExpression(const QString &pattern, QRegularExpression::PatternOptions options = NoPatternOption) | |
| QRegularExpression(const QRegularExpression &re) | |
(since 6.1) | QRegularExpression(QRegularExpression &&re) |
| ~QRegularExpression() | |
| int | captureCount() const |
| QString | errorString() const |
| QRegularExpressionMatchIterator | globalMatch(const QString &subject, qsizetype offset = 0, QRegularExpression::MatchType matchType = NormalMatch, QRegularExpression::MatchOptions matchOptions = NoMatchOption) const |
(since 6.5) QRegularExpressionMatchIterator | globalMatchView(QStringView subjectView, qsizetype offset = 0, QRegularExpression::MatchType matchType = NormalMatch, QRegularExpression::MatchOptions matchOptions = NoMatchOption) const |
| bool | isValid() const |
| QRegularExpressionMatch | match(const QString &subject, qsizetype offset = 0, QRegularExpression::MatchType matchType = NormalMatch, QRegularExpression::MatchOptions matchOptions = NoMatchOption) const |
(since 6.5) QRegularExpressionMatch | matchView(QStringView subjectView, qsizetype offset = 0, QRegularExpression::MatchType matchType = NormalMatch, QRegularExpression::MatchOptions matchOptions = NoMatchOption) const |
| QStringList | namedCaptureGroups() const |
| void | optimize() const |
| QString | pattern() const |
| qsizetype | patternErrorOffset() const |
| QRegularExpression::PatternOptions | patternOptions() const |
| void | setPattern(const QString &pattern) |
| void | setPatternOptions(QRegularExpression::PatternOptions options) |
| void | swap(QRegularExpression &other) |
| QRegularExpression & | operator=(QRegularExpression &&re) |
| QRegularExpression & | operator=(const QRegularExpression &re) |
Static Public Members
| QString | anchoredPattern(QStringView expression) |
| QString | anchoredPattern(const QString &expression) |
| QString | escape(QStringView str) |
| QString | escape(const QString &str) |
(since 6.0) QRegularExpression | fromWildcard(QStringView pattern, Qt::CaseSensitivity cs = Qt::CaseInsensitive, QRegularExpression::WildcardConversionOptions options = DefaultWildcardConversion) |
| QString | wildcardToRegularExpression(QStringView pattern, QRegularExpression::WildcardConversionOptions options = DefaultWildcardConversion) |
| QString | wildcardToRegularExpression(const QString &pattern, QRegularExpression::WildcardConversionOptions options = DefaultWildcardConversion) |
Related Non-Members
| size_t | qHash(const QRegularExpression &key, size_t seed = 0) |
| bool | operator!=(const QRegularExpression &lhs, const QRegularExpression &rhs) |
| QDataStream & | operator<<(QDataStream &out, const QRegularExpression &re) |
| QDebug | operator<<(QDebug debug, QRegularExpression::PatternOptions patternOptions) |
| QDebug | operator<<(QDebug debug, const QRegularExpression &re) |
| bool | operator==(const QRegularExpression &lhs, const QRegularExpression &rhs) |
| QDataStream & | operator>>(QDataStream &in, QRegularExpression &re) |
Detailed Description
Regular expressions, or regexps, are a very powerful tool to handle strings and texts. This is useful in many contexts, e.g.,
| Validation | A regexp can test whether a substring meets some criteria, e.g. is an integer or contains no whitespace. |
| Searching | A regexp provides more powerful pattern matching than simple substring matching, e.g., match one of the words mail, letter or correspondence, but none of the words email, mailman, mailer, letterbox, etc. |
| Search and Replace | A regexp can replace all occurrences of a substring with a different substring, e.g., replace all occurrences of & with & except where the & is already followed by an amp;. |
| String Splitting | A regexp can be used to identify where a string should be split apart, e.g. splitting tab-delimited strings. |
This document is by no means a complete reference to pattern matching using regular expressions, and the following parts will require the reader to have some basic knowledge about Perl-like regular expressions and their pattern syntax.
Good references about regular expressions include:
- Mastering Regular Expressions (Third Edition) by Jeffrey E. F. Friedl, ISBN 0-596-52812-4;
- the pcrepattern(3) man page, describing the pattern syntax supported by PCRE (the reference implementation of Perl-compatible regular expressions);
- the Perl's regular expression documentation and the Perl's regular expression tutorial.
Introduction
QRegularExpression implements Perl-compatible regular expressions. It fully supports Unicode. For an overview of the regular expression syntax supported by QRegularExpression, please refer to the aforementioned pcrepattern(3) man page. A regular expression is made up of two things: a pattern string and a set of pattern options that change the meaning of the pattern string.
You can set the pattern string by passing a string to the QRegularExpression constructor:
QRegularExpression re("a pattern");
This sets the pattern string to a pattern. You can also use the setPattern() function to set a pattern on an existing QRegularExpression object:
QRegularExpression re; re.setPattern("another pattern");
Note that due to C++ literal strings rules, you must escape all backslashes inside the pattern string with another backslash:
// matches two digits followed by a space and a word QRegularExpression re("\\d\\d \\w+"); // matches a backslash QRegularExpression re2("\\\\");
Alternatively, you can use a raw string literal, in which case you don't need to escape backslashes in the pattern, all characters between R"(...)" are considered raw characters. As you can see in the following example, this simplifies writing patterns:
// matches two digits followed by a space and a word QRegularExpression re(R"(\d\d \w+)");
The pattern() function returns the pattern that is currently set for a QRegularExpression object:
QRegularExpression re("a third pattern"); QString pattern = re.pattern(); // pattern == "a third pattern"
Pattern Options
The meaning of the pattern string can be modified by setting one or more pattern options. For instance, it is possible to set a pattern to match case insensitively by setting the QRegularExpression::CaseInsensitiveOption.
You can set the options by passing them to the QRegularExpression constructor, as in:
// matches "Qt rocks", but also "QT rocks", "QT ROCKS", "qT rOcKs", etc. QRegularExpression re("Qt rocks", QRegularExpression::CaseInsensitiveOption);
Alternatively, you can use the setPatternOptions() function on an existing QRegularExpressionObject:
QRegularExpression re("^\\d+$"); re.setPatternOptions(QRegularExpression::MultilineOption); // re matches any line in the subject string that contains only digits (but at least one)
It is possible to get the pattern options currently set on a QRegularExpression object by using the patternOptions() function:
QRegularExpression re = QRegularExpression("^two.*words$", QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption); QRegularExpression::PatternOptions options = re.patternOptions(); // options == QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption
Please refer to the QRegularExpression::PatternOption enum documentation for more information about each pattern option.
Match Type and Match Options
The last two arguments of the match() and the globalMatch() functions set the match type and the match options. The match type is a value of the QRegularExpression::MatchType enum; the "traditional" matching algorithm is chosen by using the NormalMatch match type (the default). It is also possible to enable partial matching of the regular expression against a subject string: see the partial matching section for more details.
The match options are a set of one or more QRegularExpression::MatchOption values. They change the way a specific match of a regular expression against a subject string is done. Please refer to the QRegularExpression::MatchOption enum documentation for more details.
Normal Matching
In order to perform a match you can simply invoke the match() function passing a string to match against. We refer to this string as the subject string. The result of the match() function is a QRegularExpressionMatch object that can be used to inspect the results of the match. For instance:
// match two digits followed by a space and a word QRegularExpression re("\\d\\d \\w+"); QRegularExpressionMatch match = re.match("abc123 def"); bool hasMatch = match.hasMatch(); // true
If a match is successful, the (implicit) capturing group number 0 can be used to retrieve the substring matched by the entire pattern (see also the section about extracting captured substrings):
QRegularExpression re("\\d\\d \\w+"); QRegularExpressionMatch match = re.match("abc123 def"); if (match.hasMatch()) { QString matched = match.captured(0); // matched == "23 def" // ... }
It's also possible to start a match at an arbitrary offset inside the subject string by passing the offset as an argument of the match() function. In the following example "12 abc" is not matched because the match is started at offset 1:
QRegularExpression re("\\d\\d \\w+"); QRegularExpressionMatch match = re.match("12 abc 45 def", 1); if (match.hasMatch()) { QString matched = match.captured(0); // matched == "45 def" // ... }
Extracting captured substrings
The QRegularExpressionMatch object contains also information about the substrings captured by the capturing groups in the pattern string. The captured() function will return the string captured by the n-th capturing group:
QRegularExpression re("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$"); QRegularExpressionMatch match = re.match("08/12/1985"); if (match.hasMatch()) { QString day = match.captured(1); // day == &quo