python正则表达式入门

来源:互联网 发布:电子商务大数据 编辑:程序博客网 时间:2024/05/20 19:29

基本概念

使用正则表达式需要import re

表达式前加r避免转义

\d代表数字,\s代表空白字符,\w代表字母+数字。

.代表任意单个字符

{m,n}代表前面字符至少出现m次,最多出现n次。

(xxx)括号代表分组,方便在匹配结果中取出。

(?:xxx)不分组,不能从匹配结果中单独取出,可以在后面加匹配次数。


research

只返回第一个匹配结果,不匹配则返回None.

结果.group()代表匹配结果,group(1)代表表达式中第一个()内的字符。

import retext = "inet addr:211.2.10.100  Bcast:211.2.10.255  Mask:255.255.255.0 inet addr:211.2.10.123"# find ip addressm = re.search(r"inet addr:((\d{1,3}\.){3}\d{1,3})", text)ip = m.group(1)print ip# 211.2.10.100

findall

匹配所有结果,返回列表。

如果模式中有1个(),则列表内容为分组字符串,如果有1个以上(),则列表内容为元组,元组内容为分组内容。


import rea = """tcpdump  -n -x -c 1tcpdump: WARNING: eth0: no IPv4 address assignedtcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes15:13:57.653999 IP 10.1.1.3.ssh > 10.1.1.2.60442: Flags [P.], seq 2265683999:2265684099, ack 3711911807, win 90, length 100        0x0000:  4510 008c 446b 4000 4006 50f9 0a01 0103        0x0010:  0a01 0102 0016 ec1a 870b 981f dd3f 477f        0x0020:  5018 005a a576 0000 1810 f435 f028 ef1e1 packets captured1 packets received by filter0 packets dropped by kernel """b = re.findall(r"(?: \w\w\w\w){8}", a)# b = [' 4510 008c 446b 4000 4006 50f9 0a01 0103', ' 0a01 0102 0016 ec1a 870b 981f dd3f 477f', ' 5018 005a a576 0000 1810 f435 f028 ef1e']c = re.findall(r"> (\d+.\d+.\d+.\d+)", a)# c = ['10.1.1.2']d = re.findall(r"(\d+\.\d+\.\d+\.\d+).+> (\d+\.\d+\.\d+\.\d+)", a)# d = [('10.1.1.3', '10.1.1.2')]e = re.findall(r"( \w\w\w\w){8}", a)# e = [' 0103', ' 477f', ' ef1e'], 每列最后一个。



官方文档:

http://docs.python.org/2/library/re.html