python学习之re 9 () 组

时间:2021-08-30 00:12:02

(...)Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the  \number special sequence, described below. To match the literals  '(' or  ')', use  \( or  \), or enclose them inside a character class:  [(][)].

翻译:匹配括号里面的所有的RE表达式括号代表一个组的开始和结束。组内的内容可以在匹配成功之后获取,也可以在匹配之后在string的后面添加 \xx 数字(0-99),为了匹配左右括号,可以使用转义标识符 \ 来显示,也可以添加到集合中。

\numberMatches the contents of the group of the same number. Groups are numbered starting from 1. For example,  (.+) \1 matches  'the the' or  '55 55', but not  'thethe' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of  number is 0, or  number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value  number. Inside the  '['  and  ']' of a character class, all numeric escapes are treated as characters.

匹配编号相同的组的内容,组的编号从1开始,比如 (.+) \1 匹配 'the the' 和 '55 55', 但是不匹配 'thethe' (组后面有一个空格)这种特殊的序列只能匹配前99个租,如果第一个数字为0或者是三位数八进制数,就不会按照组来进行处理,但是如果字符要表达的就是数字而不是匹配,那么可以用 []来表达,所有的数字都毫无例外的被处理为字符。

案例一

import re
string1 = "this helloa world,world world world,"
print(re.match("(.+?) \\1 \\1,",string1))
print(re.match(r"(.+?) \1 \1,",string1))
rs = re.match("(\w+ )*",string1)
print(rs.group(0))
print(rs.group(1))
输出
None
None
this helloa 
helloa 

案例二

import re
string1 = "this this this,world world world,"
print(re.match("(.+?) \\1 \\1,",string1))
print(re.match(r"(.+?) \1 \1,",string1))

输出

<re.Match object; span=(0, 15), match='this this this,'>
<re.Match object; span=(0, 15), match='this this this,'>

通过两个案例的对比我们可以看出 \1 \2这些需要在前面添加反斜杠,或者是原形前缀 r。

然后我们可以对比出\1 \2这些内容都是相同的,如果不同那么久不能匹配。

rs = re.match("(\w+ )*",string1)
print(rs.group(0))
print(rs.group(1))

这样的一段代码输出的是

this helloa 
helloa 

说明RE规则也可以通过贪心修饰符修饰  '+*?',但是所得的组是最后一个匹配项,这也就说明,不论是匹配了多少组,编号始终是不变的。是1的就是1,是2的再多还是2。