Python正则表达式re模块中有个group参数,刚开始看的时候没理解,自己摸索了一下,终于知道是啥意思了,记录一下。
先看一下教程中对这个参数的说明:
老实讲,看了这个描述我也没懂是啥意思,于是在PyCharm中试了下,才知道是啥意思,先看下代码:
#!/usr/bin/python # -*- coding: UTF-8 -*- import re def dirp(iter): # 定义函数dirp return [i for i in dir(iter) if not i.startswith(‘_‘)] # 将dir(iter)的值中过滤掉前面带_的数据后,赋值给变量i,然后将i的值赋值给dirp函数 # 定义一个变量a,并将字符串“name”赋值给变量a,字符串前面加个r是告诉编译器这个string是个raw string,不要转意 a = r"name" print(dirp(re)) # 定义一个变量match match = re.search(a, "my name is sam,what is you name?") if match: print(match.group()) # 在字符串“my name is sam,what is you name?”中搜索“name”,如果存在就打印出来 print(match.start()) # 如果有就打印该字符的开始位置,字符串“my name is sam,what is you name?”的m是第0位 print(match.end()) # 打印字符串的结束位置 print(match.span()) # 打印字符串的开始位置和结束位置 print(type(match.group)) # 打印match.group()的类型 www = r"www.cnblogs.com" print(re.match(r"(www).(cnblogs).(com)", www).group()) # 打印全部匹配结果,注意每个括号匹配值必须接上一个括号,否则会报错 print(re.match(r"(www).(cnblogs).(com)", www).group(1)) # 打印第一个括号中的匹配结果 print(re.match(r"(www).(cnblogs).(com)", www).group(2)) # 打印第二个括号中的匹配结果 print(re.match(r"(www).(cnblogs).(com)", www).group(3)) # 打印第三个括号中的匹配结果 print(re.match(r"(www).cnblogs.(com)", www).group(2)) # 打印第二个括号中的匹配结果 line = "Cars are smarter than dog." matchObj = re.match(r‘(.*) are (.*?) .*‘, line, re.M | re.I) if matchObj: print("matchObj.group(): ", matchObj.group()) print("matchObj.group(1): ", matchObj.group(1)) print("matchObj.group(2): ", matchObj.group(2)) else: print("No match!!")
执行后查看输出结果:
C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\python.exe C:\Users\Administrator\Desktop\mypython\re_test.py [‘A‘, ‘ASCII‘, ‘DEBUG‘, ‘DOTALL‘, ‘I‘, ‘IGNORECASE‘, ‘L‘, ‘LOCALE‘, ‘M‘, ‘MULTILINE‘, ‘S‘, ‘Scanner‘, ‘T‘, ‘TEMPLATE‘, ‘U‘, ‘UNICODE‘, ‘VERBOSE‘, ‘X‘, ‘compile‘, ‘copyreg‘, ‘error‘, ‘escape‘, ‘findall‘, ‘finditer‘, ‘fullmatch‘, ‘match‘, ‘purge‘, ‘search‘, ‘split‘, ‘sre_compile‘, ‘sre_parse‘, ‘sub‘, ‘subn‘, ‘sys‘, ‘template‘] name 3 7 (3, 7) <class ‘builtin_function_or_method‘> www.cnblogs.com www cnblogs com com matchObj.group(): Cars are smarter than dog. matchObj.group(1): Cars matchObj.group(2): smarter 进程已结束,退出代码0
从结果中可以看出来,group这个参数的意思就是给出多个匹配值,然后在字符串中进行匹配,然后输出对应的匹配结果,group(),这个()中的数字按从左往右的顺序1,2....进行排列(注意只有用()括起来的匹配值才算),然后还要注意就是每个匹配值之间要能接上,比如www.cnblog.con,如果匹配结果写成这样就会报错,因为匹配值之间少了个点,匹配的值就接不上:
"(www)(cnblogs)(com)"
原文:https://www.cnblogs.com/xzy186/p/14261237.html