当前时区为 UTC + 8 小时



发表新帖 回复这个主题  [ 2 篇帖子 ] 
作者 内容
1 楼 
 文章标题 : Qt正则表达式中文参考
帖子发表于 : 2015-10-26 21:04 

注册: 2010-10-31 9:15
帖子: 507
系统: kubuntu 16.04
送出感谢: 0 次
接收感谢: 13
最近要接触Qt的正则表达式部份,写了个程序根本无法得到想要的效果,网上搜索了一下也基本上是不得其解。于是只能硬着头皮看文档。看英文太累,于是花了两天时间翻译的,头都大了。终于完成了,水平有限,有错误欢迎大家指正哈。这个算是Rev 1版吧,以后如果有修正,再来修改。

QRegExp Class Reference
Qt正则表达式类参考
The QRegExp class provides pattern matching using regular expressions.
QregExp类提供使用正则表达式的匹配模式。
Public Types
enum
CaretMode { CaretAtZero, CaretAtOffset, CaretWontMatch }
enum
PatternSyntax { 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 ()
QString
cap ( int nth = 0 ) const
int
captureCount () const
QStringList
capturedTexts () const
Qt::CaseSensitivity
caseSensitivity () const
QString
errorString () const
bool
exactMatch ( const QString & str ) const
int
indexIn ( const QString & str, int offset = 0, CaretMode caretMode = CaretAtZero ) const
bool
isEmpty () const
bool
isMinimal () const
bool
isValid () const
int
lastIndexIn ( const QString & str, int offset = -1, CaretMode caretMode = CaretAtZero ) const
int
matchedLength () const
QString
pattern () const
PatternSyntax
patternSyntax () const
int
pos ( int nth = 0 ) const
void
setCaseSensitivity ( Qt::CaseSensitivity cs )
void
setMinimal ( bool minimal )
void
setPattern ( const QString & pattern )
void
setPatternSyntax ( PatternSyntax syntax )
void
swap ( QRegExp & other )
bool
operator!= ( const QRegExp & rx ) const
QRegExp &
operator= ( const QRegExp & rx )
bool
operator== ( const QRegExp & rx ) const
Static Public Members
QString
escape ( const QString & str )
Related Non-Members
QDataStream &
operator<< ( QDataStream & out, const QRegExp & regExp )
QDataStream &
operator>> ( QDataStream & in, QRegExp & regExp )

Detailed Description
The QRegExp 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.,
正则表达式是一种模式用来匹配一段文本里的子字符串。
Validation
验证
A regexp can test whether a substring meets some criteria, e.g. is an integer or contains no whitespace.
正则式能够测试子字符串是否匹配一些给定的条件。举例来说,是一个整数或是一个没有包含空格的字符串。
Searching
搜索
A regexp provides more powerful pattern matching than simple substring matching, e.g., match one of the words mail, letter or correspondence, but none of the words email, mailman, mailer, letterbox, etc.
正则式提供许多有用的匹配模式而不仅仅是简单的子字符串匹配。举例来说,匹配邮件,信件中的一个词。
Search and Replace
搜索并替换
A regexp can replace all occurrences of a substring with a different substring, e.g., replace all occurrences of & with &amp; except where the & is already followed by an amp;.
正则式能用另一个不同的字符串替换所有你想要替换的字符。举例来说,用&amp字符串替换所有的&字符。如果&后面已经有amp字符串就不会被替换,这在简单的文本替换模式中是难以实现的。
String Splitting
字符串分割
A regexp can be used to identify where a string should be split apart, e.g. splitting tab-delimited strings.
正则能够被用来识别哪里的字符应该被分割。举例来说:以tab符来分割一段包含tab符的文本。
A brief introduction to regexps is presented, a description of Qt's regexp language, some examples, and the function documentation itself.
上面是Qt正则语言的简短的介绍。
QRegExp is modeled on Perl's regexp language. It fully supports Unicode.
QRegExp是仿照Perl的正则表达式语言,完全支持Unicode,支持汉字。
QRegExp can also be used in a simpler, wildcard mode that is similar to the functionality found in command shells.
QRegExp也可以用于一个简单,通配符模式,类似于命令shell中的功能。
The syntax rules used by QRegExp can be changed with setPatternSyntax(). In particular, the pattern syntax can be set to QRegExp::FixedString, which means the pattern to be matched is interpreted as a plain string, i.e., special characters (e.g., backslash) are not escaped.
QRegExp所使用的语法规则可以用setPatternSyntax()改变。特别地,语法模式可以设置为QRegExp::FixedString ,这意味着被匹配的模式被解释为一个普通的字符串,即:特殊字符(如反斜杠)不会被漏掉了。
A good text on regexps is Mastering Regular Expressions (Third Edition) by Jeffrey E. F. Friedl, ISBN 0-596-52812-4.
正则表达式参考书《Mastering Regular Expressions (Third Edition) 》
Introduction
Regexps are built up from expressions, quantifiers, and assertions. The simplest expression is a character, e.g. x or 5. An expression can also be a set of characters enclosed in square brackets. [ABCD] will match an A or a B or a C or a D. We can write this same expression as [A-D], and an experession to match any captital letter in the English alphabet is written as [A-Z].
Regexps由表达式,量词,断言建立。最简单的表达式是一个字符。例如x或5 。一个表达式也可以是由方括号中的一系列的字符构成。例如表达式[ABCD]将匹配A或B或C或D。此表达式也可以简化成[A-D]。要一个表达式匹配所有的大写字母,可以写成[A-Z]。
A quantifier specifies the number of occurrences of an expression that must be matched. x{1,1} means match one and only one x. x{1,5} means match a sequence of x characters that contains at least one x but no more than five.
一个量词指定了一个表达式中一个号码的匹配次数。例如x{1,1}意思是匹配仅仅一个x。x{1,5}意思是匹配1至5个x。

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.
注意:一般regexps不能用来检查嵌套的标签对或括号对。
例如:一个正则式能写出匹配html里的<b>开始对和</b>结束对,如果<b>标签没有嵌套。但如果<b>是嵌套的,正则式将匹配<b>开始标签和错误的</b>。
例如<b>bold <b>bolder</b></b>,第一个<b>和第一个</b>将会被匹配。这是错误的。
不管怎样,还是有可能写出一个能匹配嵌套对的表达式的。但要求嵌套的对是已知的且是固定的。如果不是已知且固定的,那么正则式就没办法了。

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.
假设我们想要写一个匹配范围是0-99的整数的表达式,至少需要一个数字,我们先写成[0-9]{1,1},它一次精确匹配一个数字。这个表达式匹配范围为0-9的整数。要想匹配到99,需增加最大出现次数到2,所以表达式变成了[0-9]{1,2}。
这个表达式满足我们匹配原来的整数0-99的要求,但它也会匹配存在于字符串里的数字。
如果我们想要匹配存在于整个字符串里的独立的数字,我们必须使用锚断言,^(脱字符号)和$(脱字符号)。当一个正则式里的^是第一个字符时,意味着正则式必须匹配字符串的开头。
当一个正则式里的$是最后一个字符时,意味着正则式必须匹配字符串的结束。
regexp正则式变成^[0-9]{1,2}$。它的意思是匹配开头是最多2个数字,结尾最多是2个数字。
注意这个断言,例如^ and $,不会匹配字符但会定位字符串。

If you have seen regexps described elsewhere, they may have looked different from the ones shown here. This is because some sets of characters and some quantifiers are so common that they have been given special symbols to represent them.
[0-9] can be replaced with the symbol \d. The quantifier to match exactly one occurrence, {1,1}, can be replaced with the expression itself, i.e. x{1,1} is the same as x. So our 0 to 99 matcher could be written as ^\d{1,2}$. It can also be written ^\d\d{0,1}$, i.e. From the start of the string, match a digit, followed immediately by 0 or 1 digits.
In practice, it would be written as ^\d\d?$. The ? is shorthand for the quantifier {0,1}, i.e. 0 or 1 occurrences. ? makes an expression optional. The regexp ^\d\d?$ means From the beginning of the string, match one digit, followed immediately by 0 or 1 more digit, followed immediately by end of string.
如果你看见正则式被用于了其它地方,它们可能看起来跟这里的不太一样。这是因为一些量词和字符被赋予了特殊符号来表示它们。
例如[0-9]可以被符号\d替换。匹配一次的量词{1,1}就能被表达式自己替换:x{1,1}直接写成x。所以我们那个0-99的匹配式能够写成^\d{1,2}$。
还可以写成^\d\d{0,1}$,也就是从字符串的开头开始,匹配一个数字,然后跟随0或1个数字。

To write a regexp that matches one of the words 'mail' or 'letter' or 'correspondence' but does not match words that contain these words, e.g., 'email', 'mailman', 'mailer', and 'letterbox', start with a regexp that matches 'mail'. Expressed fully, the regexp is m{1,1}a{1,1}i{1,1}l{1,1}, but because a character expression is automatically quantified by {1,1}, we can simplify the regexp to mail, i.e., an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. Now we can use the vertical bar |, which means or, to include the other two words, so our regexp for matching any of the three words becomes mail|letter|correspondence.
写一个表达式来匹配一个单词”mail” 或 “letter” 或”correspondence” 但不能匹配包含这些词的复合单词。例如:”email”, “mailman”,”letterbox”等,现在先开始写一个匹配“mail”的表达式,写成m{1,1}a{1,1}i{1,1}l{1,1},因为单个字符表达式自动由{1,1}量词化,我们能简单写成mail,也就是m后跟随一个a再跟随一个i再跟随一个l。现在我们能使用竖线|,它的意思是“或”,这意味着可以用来包含其它两个单词,所以我们的正则表达式可以直接写成mail|letter|correspondence 。

Match 'mail' or 'letter' or 'correspondence'. While this regexp will match one of the three words we want to match, it will also match words we don't want to match, e.g., 'email'. To prevent the regexp from matching unwanted words, we must tell it to begin and end the match at word boundaries. First we enclose our regexp in parentheses, (mail|letter|correspondence). Parentheses group expressions together, and they identify a part of the regexp that we wish to capture. Enclosing the expression in parentheses allows us to use it as a component in more complex regexps. It also allows us to examine which of the three words was actually matched. To force the match to begin and end on word boundaries, we enclose the regexp in \b word boundary assertions: \b(mail|letter|correspondence)\b. Now the regexp means: Match a word boundary, followed by the regexp in parentheses, followed by a word boundary. The \b assertion matches a position in the regexp, not a character. A word boundary is any non-word character, e.g., a space, newline, or the beginning or ending of a string.
匹配mail或letter或correspondence三个中的一个。这个表达式也可以匹配到我们不想要的词,如email。为了阻止正则式匹配到不想要的词,我们必须告诉正则式开始匹配和结束匹配的词的边界。首先我们引入圆括号,(mail|letter|correspondence)。圆括号把表达式组合在一起,他们识别我们想要捕获的表达式的一部分。引入圆括号的表达式允许我们使用它作为更复杂的表达式的一部分。它还允许我们去检查三个里的哪个被真正匹配到了。为了强制匹配词的开始和结束边界,我们引入了\b断言。\b(mail|letter|correspondence)\b 。现在的正则式的意思是:匹配一个词的边界,紧接着是圆括号中的表达式,然后是一个词的边界。这个\b断言匹配正则式中的一个位置,而非一个字符。一个词的边界是任何非单词字符,例如一个空格,新行,或者是字符串的开始或结束字符。

If we want to replace ampersand characters with the HTML entity &amp;, the regexp to match is simply &. But this regexp will also match ampersands that have already been converted to HTML entities. We want to replace only ampersands that are not already followed by amp;. For this, we need the negative lookahead assertion, (?!__). The regexp can then be written as &(?!amp;), i.e. Match an ampersand that is not followed by amp;.
html中有&amp,如果你只想要替换html中其它的&字符,而不想替换&amp中的&,我们需要引入否定性前瞻断言(?!__) 。这时正则式能够写成&(?!amp;)。也就是匹配一个其后面不能跟随amp的&字符。

If we want to count all the occurrences of 'Eric' and 'Eirik' in a string, two valid solutions are \b(Eric|Eirik)\b and \bEi?ri[ck]\b. The word boundary assertion '\b' is required to avoid matching words that contain either name, e.g. 'Ericsson'. Note that the second regexp matches more spellings than we want: 'Eric', 'Erik', 'Eiric' and 'Eirik'.
如果我们想要计算所有的'Eric' 和'Eirik' 在一个字符串中出现的字数,两个有效的解决方案是\b(Eric|Eirik)\b 和 \bEi?ri[ck]\b 。单词边界断言\b用来避免某个单词包含其它字符,比如“Ericsson”。注意第二个表达式匹配更多的单词:'Eric', 'Erik', 'Eiric' and 'Eirik'.

Some of the examples discussed above are implemented in the code examples section.
Characters and Abbreviations for Sets of Characters
Element
Meaning
c
A character represents itself unless it has a special regexp meaning. e.g. c matches the character c.
表达式c匹配字符c
\c
A character that follows a backslash matches the character itself, except as specified below. e.g., To match a literal caret at the beginning of a string, write \^.
一个字符跟在反斜杠后面匹配匹配字符本身,除了字符串开头的脱字符\^
\a
Matches the ASCII bell (BEL, 0x07).
\f
Matches the ASCII form feed (FF, 0x0C).
\n
Matches the ASCII line feed (LF, 0x0A, Unix newline).
匹配换行符
\r
Matches the ASCII carriage return (CR, 0x0D).
匹配回车符(注:linux用\n就行,windows用\r\n,无须纠结,打字机时代的历史遗留问题)
\t
Matches the ASCII horizontal tab (HT, 0x09).
匹配tab符
\v
Matches the ASCII vertical tab (VT, 0x0B).
匹配纵向制表符
\xhhhh
Matches the Unicode character corresponding to the hexadecimal number hhhh (between 0x0000 and 0xFFFF).
以16进制匹配unicode字符,适用汉字。
\0ooo (i.e., \zero ooo)
matches the ASCII/Latin1 character for the octal number ooo (between 0 and 0377).
以8进制匹配拉丁字符,范围为8进制的0-0377
. (dot)
Matches any character (including newline).
匹配任何字符,包括新行字符。
\d
Matches a digit (Qchar::isDigit()).
匹配一个数字
\D
Matches a non-digit.
匹配一个非数字
\s
Matches a whitespace character (Qchar::isSpace()).
匹配一个空格
\S
Matches a non-whitespace character.
匹配一个非空格字符
\w
Matches a word character (QChar::isLetterOrNumber(), QChar::isMark(), or '_').
匹配一个单词
\W
Matches a non-word character.
匹配一个非单词
\n
The n-th backreference, e.g. \1, \2, etc.
匹配由n构成的数字的反向引用组,如\1,\2,\3等(需配合圆括号使用,正则系统会把圆括号编组由1开始。)
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 anything but 'a' or 'b' or 'c'.
脱字符^否定第一个出现的字符。例如[abc]是匹配a或b或c,然而[^abc]由于加上了脱字符后,意思是匹配任何字符,但偏偏不能是a或b或c 。
-
The dash indicates a range of characters. [W-Z] matches 'W' or 'X' or 'Y' or 'Z'.
破折号指定字符的范围。[W-Z]匹配W或X或Y或Z。[2-5]匹配2
或3或4或5.

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.
在跨平台上使用预定义的字符集缩写比使用范围的方式更加轻便。例如[0-9]仅在西方文字编码中匹配一个数字,但是\d在任何语言中匹配一个数字。

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.
默认情况下,一个表达式自动量化为{1,1},也就是说,它应该精确的仅出现一次。在下面的列表中,E表示为表达式。一个表达式可以是一个字符,或者是一个字符集缩写,或者是在方括号里的字符集,或者是用括号括起来的表达式。
E?
Matches zero or one occurrences of E. This quantifier means The previous expression is optional, because it will match whether or not the expression is found. E? is the same as E{0,1}. e.g., dents? matches 'dent' or 'dents'.
匹配0次或1次E。这个量词表示前面的E是可选的,因为它可以匹配0次。此表达式可改成E{0,1}。例如表达式dents?将匹配dent或dents 。

E+
Matches one or more occurrences of E. E+ is the same as E{1,}. e.g., 0+ matches '0', '00', '000', etc.
匹配1次或多次E。也可以改写成E{1,}。例如0+将匹配0 或00或00000等等。

E*
Matches zero or more occurrences of E. It is the same as E{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*$ means Match 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+$.
匹配0次或多次表达式E。等价于表达式E{0,} 。量词*通常错误地使用在应该用量词+的地方。例如,如\s*$被用来匹配末尾存在空格的字符串,其实它将匹配任何字符串,因为\s*$意思是匹配0个或多个字符串末尾的空格。正确的写法是用量词+的表达式\s+$来确定字符串末尾至少存在1个空格。

E{n}
Matches exactly n occurrences of E. E{n} is the same as repeating E n times. For example, x{5} is the same as xxxxx. It is also the same as E{n,n}, e.g. x{5,5}.
精确匹配E出现的次数。也可以写成E{n,n}。相当于重复E多次。例如x{5}等价于xxxxx。也等价于x{5,5} 。

E{n,}
Matches at least n occurrences of E.
匹配至少出现n次的E。

E{,m}
Matches at most m occurrences of E. E{,m} is the same as E{0,m}.
匹配最多出现m次的E 。也可以写成E{0,m} 。

E{n,m}
Matches at least n and at most m occurrences of E.
匹配至少n次最多m次的E 。

To apply a quantifier to more than just the preceding character, use parentheses to group characters together in an expression. For example, tag+ matches a 't' followed by an 'a' followed by at least one 'g', whereas (tag)+ matches at least one occurrence of 'tag'.
为了用量词匹配字符前面的字符,可以使用圆括号把字符组合起来。例如tag+匹配一个t一个a和至少一个g,但是(tag)+则匹配至少一次tag 。

Note: Quantifiers are normally "greedy". They always match as much text as they can. For example, 0+ matches the first zero it finds and all the consecutive zeros after the first zero. Applied to '20005', it matches'20005'. Quantifiers can be made non-greedy, see setMinimal().
注意:量词通常是贪婪的。它们总是匹配更多的可能。例如,0+匹配第一个它们找到的0和这个0后连续的0.比如20005,它一口气匹配到了三个0 。量词能够设置为非贪婪的。参阅setMinimal() 。

Capturing Text
捕获文本
Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expression mail|letter|correspondence that matches a string we know that one of the words matched but not which one. Using parentheses allows us to "capture" whatever is matched within their bounds, so if we used (mail|letter|correspondence) and matched this regexp against the string "I sent you some email" we can use the cap() or capturedTexts() functions to extract the matched characters, in this case 'mail'.
圆括号允许我们把元素组合起来以便我们能确定数量并捕获它们。例如,如果我们有个表达式 mail|letter|correspondence 匹配三个单词中的一个。使用圆括号就可以捕获任意一个。如果我们用(mail|letter|correspondence) 来匹配一个字符串"I sent you some email" ,我们能够使用cap()或者capturedTexts()函数来精确匹配字符,这里我们匹配到了“mail” 。

We can use captured text within the regexp itself. To refer to the captured text we use backreferences which are indexed from 1, the same as for cap(). For example we could search for duplicate words in a string using \b(\w+)\W+\1\b which means match a word boundary followed by one or more word characters followed by one or more non-word characters followed by the same text as the first parenthesized expression followed by a word boundary.
在表达式里我们能够捕获文本,涉及捕获文本我们使用索引从1开始的反向引用。与cap()一样。例如我们能够在一个字符串中通过使用 \b(\w+)\W+\1\b搜索重复的单词。意思是先匹配一个单词边界,然后是一个或多个单词,接着是一个或多个非单词字符,再是和第一个括号内的表达式相同的文本,最后又是一个边界。(这里的\1就是指圆括号里的\w+,反向引用。如果存在第2个圆括号,就用\2来引用)

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.
如果我们纯粹想使用圆括号组合字符而不想用于捕获。我们可以使用非捕获语法。例如(?:green|blue) 。非捕获圆括号开始于 (?: 结束于 )。这个例子中我们匹配green或blue两者之一。但没有捕获匹配。所以我们仅知道是否已匹配了但不知道到底是哪种颜色被找到了。使用非捕获圆括号比使用捕获括号更加的有效,因为正则引擎可以做更少的簿记。

Both capturing and non-capturing parentheses may be nested.
捕获和非捕获圆括号可以被嵌套。
For historical reasons, quantifiers (e.g. *) that apply to capturing parentheses are more "greedy" than other quantifiers. For example, a*(a*) will match "aaa" with cap(1) == "aaa". This behavior is different from what other regexp engines do (notably, Perl). To obtain a more intuitive capturing behavior, specify QRegExp::RegExp2 to the QRegExp constructor or call setPatternSyntax(QRegExp::RegExp2).
由于历史原因,量词(比如*)应用于捕获圆括号要比其它量词更贪婪。例如,a*(a*)将匹配“aaa”使 cap(1) = aaa 。这个行为与其它正则引擎不同(如perl)。为了获得一个更直观的捕获行为,详细指定了QRegExp::RegExp2 或调用setPatternSyntax(QRegExp::RegExp2)。

When the 不of matches cannot be determined in advance, a common idiom is to use cap() in a loop. For example:
当匹配数量不能预先决定,一个通用的诀窍是在循环中使用cap(),如下所示:

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 list E stands for any expression.
断言创造一些关于出现在正则式中的文本的位置而不匹配任何字符的声明。如下:
^
The caret signifies the beginning of the string. If you wish to match a literal ^ you must escape it by writing \\^. For example, ^#include will only match strings which begin with the characters '#include'.
(When the caret is the first character of a character set it has a special meaning, see Sets of Characters.)
脱字符指字符串的最开始的地方。如果你想要匹配普通字符^,你必须写成\\^。例如^#include将仅匹配#include开头的字符串。(当 ^是一个字符集首的时候有特殊含义,指排除)
$
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 \\$.
美元符号指在字符串末尾。例如\d\s*$会匹配末尾是一个数字或空格的字符串。同样如果你想匹配普通字符$,你要写成\\$的形式。
\b
A word boundary. For example the regexp \bOK\b means match immediately after a word boundary (e.g. start of string or whitespace) the letter 'O' then the letter 'K' immediately before another word boundary (e.g. end of string or whitespace). But note that the assertion does not actually match any whitespace so if we write (\bOK\b) and we have a match it will only contain 'OK' even if the string is "It's OK now".
单词边界。例如 \bOK\b 指匹配OK,这个OK前后有空格或OK在字符串最开始的地方或结束的地方。但要注意此断言不匹配空格。所以我们写的这个断言仅包含OK,哪怕OK左右都是空格。"It's OK now".
\B
A non-word boundary. This assertion is true wherever \b is false. For example if we searched for \Bon\B in "Left on" the match would fail (space and end of string aren't non-word boundaries), but it would match in "tonne".
非单词边界。此断言当\b断言为假时为真。例如我们在字符串Left on 中搜索\Bon\B,匹配失败(空格和尾字符不是非单词边界),但它可以匹配tonne 。因为tonne中的on不是一个独立的单词。
(?=E)
Positive lookahead. This assertion is true if the expression matches at this point in the regexp. For example, const(?=\s+char) matches 'const' whenever it is followed by 'char', as in 'static const char *'. (Compare with const\s+char, which matches 'static const char *'.)
先行断言。此断言为真的条件是表达式匹配某个位置。例如:const(?=\s+char) 匹配const每当它跟随在char后,就像在static const char * 中(对于表达式const\s+char来说,它匹配static const char *)
(?!E)
Negative lookahead. This assertion is true if the expression does not match at this point in the regexp. For example, const(?!\s+char) matches 'const' except when it is followed by 'char'.
负向先行断言。此断言为真的条件是表达式不匹配某个位置。例如const(?!\s+char) 的意思是当char后跟随const时匹配失败。
Wildcard Matching
通配符匹配
Most command shells such as bash or cmd.exe support "file globbing", the ability to identify a group of files by using wildcards. The setPatternSyntax() function is used to switch between regexp and wildcard mode. Wildcard matching is much simpler than full regexps and has only four features:
许多命令行shell,例如bash或cmd.exe支持文件名替换。通过使用通配符能识别文件的类型。setPatternSyntax() 函数用来在正则和通配符之间转换。通配符匹配比全功能的正则要简单许多,它只有4种类型:

c
Any character represents itself apart from those mentioned below. Thus c matches the character c.
任何字符代表它本身(除了下面提到的),因此c匹配一个字符c 。
?
Matches any single character. It is the same as . in full regexps.
匹配所有单个字符。在正则式中和.的作用是一样的。
*
Matches zero or more of any characters. It is the same as .* in full regexps.
匹配0个或多个任意字符。相当于正则中的.* 。
[...]
Sets of characters can be represented in square brackets, similar to full regexps. Within the character class, like outside, backslash has no special meaning.
字符集能够用方括号来表示,跟正则相似。其中反斜杠无特别意义。
In the mode Wildcard, the wildcard characters cannot be escaped. In the mode WildcardUnix, the character '\' escapes the wildcard.
For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with *.html. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'.
在通配符模式,通配符不能被避开。在 WildcardUnix模式,字符\能够避开通配符。
例如我们在通配符模式下,并且有一个字符串包含文件名,我们能够以*.html 来识别HTML文件。这将匹配0个或多个字符后面跟随.字符,再跟随h,t,m,l 。

To test a string against a wildcard expression, use exactMatch(). For example:
QRegExp rx("*.txt");
rx.setPatternSyntax(QRegExp::Wildcard);//设置为通配符模式
rx.exactMatch("README.txt"); // returns true
rx.exactMatch("welcome.txt.bak"); // returns false
Notes for Perl Users
Perl用户请注意
Most of the character class abbreviations supported by Perl are supported by QRegExp, see characters and abbreviations for sets of characters.
大部份被Perl支持的字符类型缩写同样被QRegExp支持。
In QRegExp, apart from within character classes, ^ always signifies the start of the string, so carets must always be escaped unless used for that purpose. In Perl the meaning of caret varies automagically depending on where it occurs so escaping it is rarely necessary. The same applies to $ which in QRegExp always signifies the end of the string.
在QRegExp中,除了在字符类,^总是表示字符串的开始,所以脱字符必须总是被避开除非用于以上那个目的。而在Perl中^的意思则自动地依靠它所出现的位置。相同的是$在QRegExp中总是表示字符串的结尾。
QRegExp's quantifiers are the same as Perl's greedy quantifiers (but see the note above). Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regexp ro+?m requires:
QRegExp的量词跟Perl的贪婪量词一样。非贪婪匹配不能被应用于个体量词。但能被用于在模式中的所有量词。例如,要匹配perl正则的ro+?m要求:
QRegExp rx("ro+m");
rx.setMinimal(true);
The equivalent of Perl's /i option is setCaseSensitivity(Qt::CaseInsensitive).
跟Perl的/i参数相同的是setCaseSensitivity(Qt::CaseInsensitive)。
Perl's /g option can be emulated using a loop.
用循环能够模拟Perl的/g选项。
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.
在QRegExp中,匹配任何字符,所有QRegExp正则有跟Perl的/s相同的功能。
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.
因为QRegExp是面向字符串的,没有Perl里的\A,\Z或\z断言。也不支持\G断言但可通过循环来模拟。
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.
Perl的$&是cap(0)或capturedTexts()[0] 。对于$`,$' 或$+,QRegExp没有相似的功能。Perl的捕获变量$1,$2,….则符合QRegExt中的cap(1) , cap(2) , …….
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:
不支持Perl的扩展/x语法,指令也不支持,例如(?i),或正则注释(?#comment)。另一方面,C++对字面值字符串的规则是能够被用来完成相同的功能:
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.
零宽先行断言(?=pattern) 和负向先行断言(?!pattern) 以相同的Perl语法被支持。而后行断言,独立的子表达式和条件表达式则不被支持。
Non-capturing parentheses are also supported, with the same (?:pattern) syntax.
非捕获圆括号是被支持的,有相同的语法(?:pattern) 。
See QString::split() and QStringList::join() for equivalents to Perl's split and join functions.
Perl中的分割和连接功能可参考QString::split() 和 QStringList::join() 。
Note: because C++ transforms \'s they must be written twice in code, e.g. \b must be written \\b.
注意:由于C++ 的转换,\必须写2次。例如\b 必须写成 \\b.
Code Examples
代码示例
QRegExp rx("^\\d\\d?$"); // match integers 0 to 99
rx.indexIn("123"); // returns -1 (no match)
rx.indexIn("-6"); // returns -1 (no match)
rx.indexIn("6"); // returns 0 (matched as position 0)
The third string matches '6'. This is a simple validation regexp for integers in the range 0 to 99.
第三个字符串匹配到了 '6' 。(?号匹配0次或1次)

QRegExp rx("^\\S+$"); // match strings without whitespace
rx.indexIn("Hello world"); // returns -1 (no match)
rx.indexIn("This_is-OK"); // returns 0 (matched at position 0)
The second string matches 'This_is-OK'. We've used the character set abbreviation '\S' (non-whitespace) and the anchors to match strings which contain no whitespace.
第二个字符串匹配到了 'This_is-OK' 。(+号匹配1次或多次)

In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email'
下面的例子我们匹配字符串,它包含'mail' 或 'letter' 或 'correspondence' ,但必须包含整个单词,不能包含像email之类的单词。

QRegExp rx("\\b(mail|letter|correspondence)\\b");
rx.indexIn("I sent you an email"); // returns -1 (no match)
rx.indexIn("Please write the letter"); // returns 17
The second string matches "Please write the letter". The word 'letter' is also captured (because of the parentheses). We can see what text we've captured like this:
第二个字符串匹配到了"Please write the letter" (因为有圆括号)。我们可以用下面的方法看什么字符串被捕获到了。

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).
这会从捕获圆括号里捕获文本。捕获是从cap(1)开始的。因为cap(0)是存储的整个匹配到的正则式。

QRegExp rx("&(?!amp;)"); // match ampersands but not &amp;
QString line1 = "This & that"; //匹配&但不包含&amp中的&;
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.
这里我们把QRegExp传递给了QString的replace()函数去替换匹配到的文本。

QString str = "One Eric another Eirik, and an Ericsson. "
"How many Eiriks, Eric?";
QRegExp rx("\\b(Eric|Eirik)\\b"); // match Eric or Eirik
int pos = 0; // where we are in the string
int count = 0; // how many Eric and Eirik's we've counted
while (pos >= 0) {
pos = rx.indexIn(str, pos);
if (pos >= 0) {
++pos; // move along in str
++count; // count our Eric or Eirik
}
}
We've used the indexIn() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time pos++ we could have written pos += rx.matchedLength() to skip over the already matched string. The count will equal 3, matching 'One Eric another Eirik, and an Ericsson. How many Eiriks, Eric?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries.
我们使用了indexIn() 函数在字符串中重复匹配正则。注意代替一次前移一个字符pos++可以写成pos += rx.matchedLength() 来跳过已经匹配到的字符串。匹配数量等于3,匹配到'One Eric another Eirik, and an Ericsson. How many Eiriks, Eric?';它没有匹配到'Ericsson' 或 'Eiriks' 是因为它们没有边界。
One common use of regexps is to split lines of delimited data into their component fields.
正则的一个通常的用法是分割带分割符的行。
str = "Nokia Corporation\tqt.nokia.com\tNorway";
QString company, web, country;
rx.setPattern("^([^\t]+)\t([^\t]+)\t([^\t]+)$");
if (rx.indexIn(str) != -1) {
company = rx.cap(1);
web = rx.cap(2);
country = rx.cap(3);
}
In this example our input lines have the format company name, web address and country. Unfortunately the regexp is rather long and not very versatile -- the code will break if we add any more fields. A simpler and better solution is to look for the separator, '\t' in this case, and take the surrounding text. The QString::split() function can take a separator string or regexp as an argument and split a string accordingly.
在这个例子中,我们输入的行是带有格式的公司名,网络地址和国家。糟糕的是正则相当的长,还很不通用。如果我们添加更多的字段,代码将终止。一个简单有效的办法是分割它们。这个例子是\t符号
QString::split()函数能够分割字符串或正则作为一个参数也可以用来分割字符串。
QStringList field = str.split("\t");
Here field[0] is the company, field[1] the web address and so on.
这里 field[0] = company,field[1] = web address ,诸如此类。
To imitate the matching of a shell we can use wildcard mode.
为了模仿shell的匹配,我们可以用通配符模式。
QRegExp rx("*.html");
rx.setPatternSyntax(QRegExp::Wildcard);
rx.exactMatch("index.html"); // returns true
rx.exactMatch("default.htm"); // returns false
rx.exactMatch("readme.txt"); // returns false
Wildcard matching can be convenient because of its simplicity, but any wildcard regexp can be defined using full regexps, e.g. .*\.html$. Notice that we can't match both .html and .htm files with a wildcard unless we use *.htm* which will also match 'test.html.bak'. A full regexp gives us the precision we need, .*\.html?$.
通配符匹配因为简单所以便利。但任何通配符正则能够被定义使用全功能的正则。例如改成 .*\.html$ 。注意此表达式不能匹配.html 和.htm 两者。只能匹配.html 。除非改写成 *.htm* 。但这会匹配到不想要的文本,比如test.html.bak 。全功能的正则给了我们精确的能力 .*\.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).
QRegExp用setCaseSensitivity()函数能够匹配需要区分大小写的字符串。也能使用非贪婪模式,请参阅 setMinimal() 。默认情况下QRegExp使用完整的正则,您可以通过setWildcard()来改变。还有一些如indexIn(),lastIndexIn(),capturedTexts(),cap(),pos() 函数请自行参阅帮助文档。
附件:
QRegExp class 参考.odt [50.16 KiB]
被下载 82 次


_________________
百度网盘 2048G容量 大放送!
百度网盘资源论坛一键保存资源!


页首
 用户资料  
 
2 楼 
 文章标题 : Re: Qt正则表达式中文参考
帖子发表于 : 2017-07-25 9:49 

注册: 2017-07-10 12:31
帖子: 1
系统: Ubuntu
送出感谢: 0 次
接收感谢: 0 次
Mark,不支持后行断言,我说怎么总匹配不对


页首
 用户资料  
 
显示帖子 :  排序  
发表新帖 回复这个主题  [ 2 篇帖子 ] 

当前时区为 UTC + 8 小时


在线用户

正在浏览此版面的用户:没有注册用户 和 2 位游客


不能 在这个版面发表主题
不能 在这个版面回复主题
不能 在这个版面编辑帖子
不能 在这个版面删除帖子
不能 在这个版面提交附件

前往 :  
本站点为公益性站点,用于推广开源自由软件,由 DiaHosting VPSBudgetVM VPS 提供服务。
我们认为:软件应可免费取得,软件工具在各种语言环境下皆可使用,且不会有任何功能上的差异;
人们应有定制和修改软件的自由,且方式不受限制,只要他们自认为合适。

Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
简体中文语系由 王笑宇 翻译