Regular Expression Syntax

python的正则表达式

正则表达式的概念

正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。

给定一个正则表达式和另一个字符串,我们可以达到如下的目的:

  1. 给定的字符串是否符合正则表达式的过滤逻辑(称作“匹配”);
  2. 可以通过正则表达式,从字符串中获取我们想要的特定部分。
    正则表达式的特点是:
  3. 灵活性、逻辑性和功能性非常强;
  4. 可以迅速地用极简单的方式达到字符串的复杂控制。
  5. 对于刚接触的人来说,比较晦涩难懂。
    由于正则表达式主要应用对象是文本,因此它在各种文本编辑器场合都有应用,小到著名编辑器EditPlus,大到Microsoft Word、Visual Studio等大型编辑器,都可以使用正则表达式来处理文本内容。

python的正则

由于正则表达式在各个语言和系统中都有所差异,所以从官网搬来原文,稍加整理,仅供参考
PS:为什么要搬原文?因为踩过坑,说起来都是泪

python的re模块提供了与Perl中类似的正则表达式匹配操作。要搜索的模式和字符串都可以是Unicode字符串,也可以是8位字符串。

python官网正则简介

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO.

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like 'A', 'a', or '0', are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. (In the rest of this section, we’ll write RE’s in this special style, usually without quotes, and strings to be matched 'in single quotes'.)

Some characters, like '|' or '(', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using the umber notation, e.g., 'x00'.

Repetition qualifiers (, +, ?, {m,n}, etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix ?, and with other modifiers in other implementations. To apply a second repetition to an inner repetition, parentheses may be used. For example, the expression (?:a{6}) matches any multiple of six 'a' characters.

解释一下(英语学渣,说的不好见谅,要是有翻译错误请留言,我会及时修改PS:翻译了半天,发现还是谷歌翻译的好,索性拿来用了)

正则表达式可以包含特殊字符和普通字符。大多数普通字符,比如'A','a'或者'0'是最简单的正则表达式; 他们只是匹配自己。你可以连接普通字符,让last匹配字符串'last'。

一些字符,如'|'或者'(',是特殊的。特殊字符代表普通字符的类,或者影响它们周围正则表达式的解释方式。正则表达式模式字符串不能包含空字节,但可以使用 umber符号来指定空字节,例如'x00'。

重复限定符(,+,?,{m,n},等等)不能直接嵌套。这避免了非贪婪修饰符后缀?和其他修饰符在其他实现中的歧义 。要将第二个重复应用于内部重复,可以使用括号。例如,表达式(?:a{6})匹配六个'a'字符的任意倍数。

re模块支持的正则

re模块git链接

The special characters are:

符号 英文释义 中文释义
"." Matches any character except a newline. (点)。在默认模式下,它匹配除换行符以外的任何字符。
"^" Matches the start of the string. (插入符)匹配字符串的开头
"$" Matches the end of the string or just before the newline at the end of the string. 匹配字符串的结尾或紧跟在字符串末尾的换行符之前, foo 匹配'foo'和'foobar',而正则表达式foo$只匹配'foo'。
"*" Matches 0 or more (greedy) repetitions of the preceding RE.Greedy means that it will match as many repetitions as possible. 使得到的RE匹配前面的RE的0个或更多个重复,尽可能多的重复。 ab*将匹配“a”,“ab”或“a”,后跟任意数量的“b”。
"+" Matches 1 or more (greedy) repetitions of the preceding RE. 使得到的RE匹配前面RE的一个或多个重复。 ab+将匹配“a”,然后匹配任何非零数字的“b”; 它不会仅仅匹配'a'。
"?" Matches 0 or 1 (greedy) of the preceding RE. 使得到的RE匹配前面RE的0或1次重复。 ab?将匹配“a”或“ab”。
*?,+?,?? Non-greedy versions of the previous three special characters. '*','+'和'?'都是贪婪的 ; 他们匹配尽可能多的文字。有时这种行为是不希望的;re.match(r'^(d+?)(0*)$', '102300').groups()匹配的结果('1023', '00');若使用^(d+)(0*)$结果为('102300', '')
{m} 指定应该匹配前一个RE的正好m个副本; 更少的匹配导致整个RE不匹配。例如,a{6}将恰好匹配六个'a'字符,但不是五个。
{m,n} Matches from m to n repetitions of the preceding RE. 匹配前面的RE的m到n次重复,试图匹配尽可能多的重复。例如, a{3,5}将匹配3到5个'a'字符。省略m指定零的下限,省略n指定无限上限。作为一个例子,a{4,}b将会匹配aaaab一千个'a'字符,然后是一个b,但不是aaab。逗号不得省略,否则修饰符会与之前描述的形式混淆。
{m,n}? Non-greedy version of the above. 使得到的RE匹配前面的RE的m到n个重复,试图匹配尽可能少的重复。这是以前限定符的非贪婪版本。例如,在6个字符的字符串中'aaaaaa',a{3,5}将匹配5个'a'字符,而a{3,5}?只匹配3个字符。
"\" Either escapes special characters or signals a special sequence. 可以转义特殊字符或发出特殊的序列。
[] Indicates a set of characters.A "^" as the first character indicates a complementing set. 表示一组字符。[^a]表示取a的补集
"|" A|B, creates an RE that will match either A or B. A | B,创建一个匹配A或B的RE;或运算
(...) Matches the RE inside the parentheses.The contents can be retrieved or matched later in the string. 匹配括号内的任何正则表达式,并指示组的开始和结束; 一个组的内容可以在匹配完成后被检索到,并且可以在 umber 下面描述的特殊序列的字符串中进行匹配。要匹配的文字'('或')'使用(或),或将它们括字符类中:。[(] [)]
(?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below). 为RE设置A,I,L,M,S,U或X标志(见下文)。
(?:...) Non-grouping version of regular parentheses. (...)的不分组版本,用于使用'|'或后接数量词。; (?:abc){2} ;abcabc
(?P...) The substring matched by the group is accessible by name. 对指定组的反向引用; 它匹配任何文本是由早些时候被任命为组匹配的名称。
(?P=name) Matches the text matched earlier by the group named name. 匹配名为name的组之前匹配的文本。
(?#...) A comment; ignored. #后的内容作为注释被忽略
(?=...) Matches if ... matches next, but doesn't consume the string. 匹配if ...匹配next,但不消耗字符串。
(?!...) Matches if ... doesn't match next. 匹配如果...下一个不匹配。
(?<=...) Matches if preceded by ... (must be fixed length). 如果...之前匹配(必须是固定长度)。
(?<!...) Matches if not preceded by ... (must be fixed length). 如果不匹配,则匹配...(必须是固定的长度)。
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,the (optional) no pattern otherwise. 匹配是模式,如果与ID /名称匹配的组,(可选的)否则没有模式。

The special sequences consist of "\" and a character from the list below.If the ordinary character is not on the list, then the resulting RE will match the second character.
除了特殊字符还有一些包含特殊含义的脱义字符

符号 英文释义 中文释义
umber Matches the contents of the group of the same number. 数字匹配相同数字的组的内容。
A Matches only at the start of the string. 仅匹配字符串的开头。
 Matches only at the end of the string. 仅匹配字符串的末尾。
 Matches the empty string, but only at the start or end of a word. 匹配空字符串,但只匹配单词的开头或结尾。
B Matches the empty string, but not at the start or end of a word. 匹配空字符串,但不匹配单词的开头或结尾。
d Matches any decimal digit; equivalent to the set [0-9] in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag,it will match the whole range of Unicode digits. 匹配任何十进制数字;相当于集合[0-9]中字节模式或字符串模式与ASCII标志。在没有ASCII标志的字符串模式中,它将匹配整个Unicode数字的范围。
D Matches any non-digit character; equivalent to [^d]. 匹配任何非数字字符;相当于[^d]。
s Matches any whitespace character; equivalent to [ fv] in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the whole range of Unicode whitespace characters. 匹配任何空格字符;相当于[ fv]中字节模式或字符串模式与ASCII标志。在没有ASCII标志的字符串模式中,它将匹配整个Unicode空白字符的范围。
S Matches any non-whitespace character; equivalent to [^s]. 匹配任何非空白字符;相当于[^ s]。
w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the range of Unicode alphanumeric characters (letters plus digits plus underscore).With LOCALE, it will match the set [0-9_] plus characters defined as letters for the current locale. 匹配任何字母数字字符;相当于[a-zA-Z0-9_]以ASCII为单位的字节模式或字符串模式在没有ASCII标志的字符串模式中,它将匹配Unicode字母数字字符(字母加数字)的范围加下划线)使用LOCALE,它将匹配集合[0-9_]加上定义的字符作为当前语言环境的信件。
W Matches the complement of w. 匹配 w的补码。
\ Matches a literal backslash. 匹配一个文字反斜杠。

(注意用来表示单词的边界,只在字符类中表示“退格”)。


'':

脱义特殊字符(允许您匹配像'*','?'等等字符 ),python中的""会优先被作为脱义字符,其他特殊符号也一样

[]:

用于表示一组字符。在一组中:

如[amk]将匹配'a', 'm'或'k'。
字符的范围可以通过给两个字符,并通过把它们分开来表示'-',例如[a-z]将匹配任何小写ASCII字母, [0-5][0-9]将所有的后两位数字从匹配00到59,并 [0-9A-Fa-f]会匹配任何十六进制数字。如果-被转义(例如 [a-z])或者被放置为第一个或最后一个字符(例如[a-]),它将匹配文字'-'。
特殊字符在集合内部失去了特殊的含义。例如, [(+)]将匹配任何文字字符的'(','+', '',或')'。
字符类,如(w或S定义如下)也被接受在一个集合内,尽管他们匹配的字符取决于是否 LOCALE或 UNICODE模式是有效的。
不在一个范围内的字符可以通过 对该集合进行补充来匹配。如果该集合的第一个字符是'',所有不在集合中的字符将被匹配。例如,[5]将匹配除了任何字符'5',[^^]并将匹配除任何字符 '^'。 ^如果它不是集合中的第一个字符,那么它没有特别的意义。
要匹配一个']'集合中的一个字面值,在它之前加一个反斜杠,或者把它放在集合的开头。例如,无论是[()[]{}]和 [{}]都将匹配一个括号。

'|':

A|B,其中A和B可以是任意RE,创建一个匹配A或B的正则表达式。任意数量的RE可以用'|'这种方式分开 。这可以在组内使用(见下文)。当扫描目标字符串时,'|'从左到右尝试分隔的RE 。当一个模式完全匹配时,该分支被接受。这意味着一旦A匹配,B将不会进一步测试,即使它会产生更长的整体匹配。换句话说,'|'操作员从来不贪婪。为了匹配一个文字'|',使用|或者把它放在一个字符类中,就像[|]。

(?...):

这是一个扩展符号('?'后面的a '('不是有意义的)。之后的第一个字符'?'决定了构造的含义和进一步的语法。扩展通常不会创建一个新的组; (?P...)是这个规则的唯一例外。以下是当前支持的扩展。

(?aiLmsux):

(从所述一组一个或多个字母'a'.'i','L','m','s', 'u','x'。)该组匹配空字符串; 这些字母为整个正则表达式设置了相应的标志:(re.I忽略大小写), re.L(区域依赖),re.M(多行), re.S(点全部匹配),re.U(与Unicode相关)和re.X(详细)。(这些标志在“ 模块内容”中进行了描述。)如果您希望将标志作为正则表达式的一部分包含在内,而不是将标志参数传递给 re.compile()函数,那么这非常有用。

请注意,该(?x)标志更改了表达式的解析方式。它应该首先在表达式字符串中使用,或者在一个或多个空白字符之后使用。如果在标志之前有非空白字符,结果是不确定的。

(?P<name>...):

类似于普通括号,但该组匹配的子字符串是通过符号组名称访问的名称。组名称必须是有效的Python标识符,每个组名称只能在正则表达式中定义一次。一个象征性的小组也是一个有编号的小组,就像这个小组没有被命名一样。

命名组可以在三个上下文中被引用。如果模式是 (?P['"]).*?(?P=quote)(即匹配用单引号或双引号引用的字符串):

参考组“引用”的语境 使用方法
在相同的模式本身 (?P=quote) (如图所示)
- 1
处理匹配对象时 m m.group('quote')
- m.end('quote') (等等。)
在传递给repl 参数的字符串中re.sub() g
- g<1>
- 1

(?aiLmsux)、(?:...)、(?P<name>...) 、(?P=name)、(?#...)、(?=...)、(?!...)、(?<=...)、(?<!...)、(?(id/name)yes|no)

这些特殊的正则因为使用的不多,并不了解使用方法,翻译并不准确;以英文版为准

原文地址:https://www.cnblogs.com/irockcode/p/7909874.html