- 时间:2021-05-27 10:11 编辑: 来源: 阅读:
- 扫一扫,手机访问
摘要:教你学会使用Python正则表达式
[img]http://files.jb51.net/file_images/article/201709/201709070839061.jpg[/img]
今天写爬虫偶然想到了初学正则表达式时候,看过一篇文章非常不错。检索一下还真的找到了。
[b]re模块[/b]
[img]http://files.jb51.net/file_images/article/201709/201709070839062.png[/img]
[code]re.search[/code]
经常用match = re.search(pat, str)的形式。因为有可能匹配不到,所以re.search()后面一般用if statement。
[img]http://files.jb51.net/file_images/article/201709/201709070839073.png[/img]
[code]re.match[/code]
re.match和re.search很相似,只是re.match是从字符串的开头开始匹配。
[img]http://files.jb51.net/file_images/article/201709/201709070839074.png[/img]
常用正则字符意义 a, X, 9,等字符匹配自己, 元字符不匹配自己,因为有特殊意义,比如 . ^ $ * + ? { }[ ] \ | ( ) . 英文句号,匹配任意字符,不包含'\n' \w 匹配'word'字符,[a-zA-Z0-9] \W 匹配非'word'字符 \b 匹配'word'和'non-word'之间边界 \s 匹配单个whitespace字符,space, newline, return, tab, form [\n\r\t\f] \S 匹配non-whitespace字符 \t, \n, \r 匹配tab, newline, return \d 匹配数字[0-9] ^ 匹配字符串开头 $ 匹配字符串结尾 重复
‘+' 一或多次, ‘*' 零或多次, ‘?' 零或一次
[code]方括号[][/code]
[img]http://files.jb51.net/file_images/article/201709/201709070839075.png[/img]
[code][]类似于or[/code]
Square brackets can be used to indicate a set of chars, so [abc] matches 'a' or 'b' or 'c'.
[img]http://files.jb51.net/file_images/article/201709/201709070839076.png[/img]
[code]Group Extraction圆括号()[/code]
有时候需要提取匹配字符的一部分,比如刚才的邮箱,我们可能需要其中的username和hostname,这时候可以用()分别把username和hostname包起来,就像r'([\w.-]+)@([\w.-]+)',如果匹配成功,那么pattern不改变,只是可以用match.group(1)和match.group(2)来username和hostname,match.group()结果不变。
[img]http://files.jb51.net/file_images/article/201709/201709070839077.png[/img]
[code]findall and groups[/code]
()和findall()结合,如果包括一或多个group,就返回a list of tuples。
[img]http://files.jb51.net/file_images/article/201709/201709070839078.png[/img]
给re.search加^之后是一样的。
[code]re.sub[/code]
re.sub(pat, replacement, str)在str里寻找和pattern匹配的字符串,然后用replacement替换。replacement可以包含\1或者\2来代替相应的group,然后实现局部替换。 [img]http://files.jb51.net/file_images/article/201709/201709070839079.png[/img]