- 正则表达式(可以称为REs,regex,regex pattens)是一个小巧的,高度专业化的编程语言,它内嵌于python开发语言中,可通过re模块使用。正则表达式的
-
- pattern可以被编译成一系列的字节码,然后用C编写的引擎执行。下面简单介绍下正则表达式的语法
-
- 正则表达式包含一个元字符(metacharacter)的列表,列表值如下: . ^ $ * + ? { [ ] \ | ( )
-
- 1.元字符([ ]),它用来指定一个character class。所谓character classes就是你想要匹配的字符(character)的集合.字符(character)可以单个的列出,也可以通过"-"来分隔两个字符来表示一个范围。例如,[abc]匹配a,b或者c当中任意一个字符,[abc]也可以用字符区间来表示---[a-c].如果想要匹配单个大写字母,你可以用[A-Z]。
-
- 元字符(metacharacters)在character class里面不起作用,如[akm$]将匹配"a","k","m","$"中的任意一个字符。在这里元字符(metacharacter)"$"就是一个普通字符。
-
- 2.元字符[^]. 你可以用补集来匹配不在区间范围内的字符。其做法是把"^"作为类别的首个字符;其它地方的"^"只会简单匹配 "^"字符本身。例如,[^5] 将匹配除 "5" 之外的任意字符。同时,在[ ]外,元字符^表示匹配字符串的开始,如"^ab+"表示以ab开头的字符串。
-
- 举例验证,
-
- >>> m=re.search("^ab+","asdfabbbb")
- >>> print m
- None
- >>> m=re.search("ab+","asdfabbbb")
- >>> print m
- <_sre.SRE_Match object at 0x011B1988>
- >>> print m.group()
- abbbb
-
- 上例不能用re.match,因为match匹配字符串的开始,我们无法验证元字符"^"是否代表字符串的开始位置。
-
- >>> m=re.match("^ab+","asdfabbbb")
- >>> print m
- None
- >>> m=re.match("ab+","asdfabbbb")
- >>> print m
- None
-
- #验证在元字符[]中,"^"在不同位置所代表的意义。
- >>> re.search("[^abc]","abcd") #"^"在首字符表示取反,即abc之外的任意字符。
- <_sre.SRE_Match object at 0x011B19F8>
- >>> m=re.search("[^abc]","abcd")
- >>> m.group()
- 'd'
- >>> m=re.search("[abc^]","^") #如果"^"在[ ]中不是首字符,那么那就是一个普通字符
- >>> m.group()
- '^'
-
- 不过对于元字符”^”有这么一个疑问.官方文档http://docs./library/re.html有关元字符”^”有这么一句话,Matches the start
-
- of the string, and in MULTILINE mode also matches immediately after each newline.
-
- 我理解的是”^”匹配字符串的开始,在MULTILINE模式下,也匹配换行符之后。
-
- >>> m=re.search("^a\w+","abcdfa\na1b2c3")
-
- >>> m.group()
-
- 'abcdfa'
-
- >>> m=re.search("^a\w+","abcdfa\na1b2c3",re.MULTILINE),
-
- >>> m.group() #
-
- 'abcdfa'
-
- 我认为flag设定为re.MULTILINE,根据上面那段话,他也应该匹配换行符之后,所以应该有m.group应该有"a1b2c3",但是结果没有,用findall来尝试,可以找到结果。所以这里我理解之所以group里面没有,是因为search和match方法是匹配到就返回,而不是去匹配所有。
-
- >>> m=re.findall("^a\w+","abcdfa\na1b2c3",re.MULTILINE)
-
- >>> m
-
- ['abcdfa', 'a1b2c3']
-
-
-
- 3. 元字符(\),元字符backslash。做为 Python 中的字符串字母,反斜杠后面可以加不同的字符以表示不同特殊意义。
-
- 它也可以用于取消所有的元字符,这样你 就可以在模式中匹配它们了。例如,如果你需要匹配字符 "[" 或 "\",你可以在它们之前用反斜杠来取消它们的特殊意义: \[ 或 \\
-
- 4。元字符($)匹配字符串的结尾或者字符串结尾的换行之前。(在MULTILINE模式下,"$"也匹配换行之前)
-
- 正则表达式"foo"既匹配"foo"又匹配"foobar",而"foo$"仅仅匹配"foo".
-
-
-
- >>> re.findall("foo.$","foo1\nfoo2\n")#匹配字符串的结尾的换行符之前。
- ['foo2']
-
- >>> re.findall("foo.$","foo1\nfoo2\n",re.MULTILINE)
- ['foo1', 'foo2']
-
- >>> m=re.search("foo.$","foo1\nfoo2\n")
- >>> m
- <_sre.SRE_Match object at 0x00A27170>
- >>> m.group()
- 'foo2'
- >>> m=re.search("foo.$","foo1\nfoo2\n",re.MULTILINE)
- >>> m.group()
- 'foo1'
-
- 看来re.MULTILINE对$的影响还是蛮大的。
-
- 5.元字符(*),匹配0个或多个
-
- 6.元字符(?),匹配一个或者0个
-
- 7.元字符(+), 匹配一个或者多个
- 8,元字符(|), 表示"或",如A|B,其中A,B为正则表达式,表示匹配A或者B
-
- 9.元字符({})
-
- {m},用来表示前面正则表达式的m次copy,如"a{5}",表示匹配5个”a”,即"aaaaa"
-
- >>> re.findall("a{5}","aaaaaaaaaa")
- ['aaaaa', 'aaaaa']
- >>> re.findall("a{5}","aaaaaaaaa")
- ['aaaaa']
-
- {m.n}用来表示前面正则表达式的m到n次copy,尝试匹配尽可能多的copy。
-
- >>> re.findall("a{2,4}","aaaaaaaa")
- ['aaaa', 'aaaa']
- 通过上面的例子,可以看到{m,n},正则表达式优先匹配n,而不是m,因为结果不是["aa","aa","aa","aa"]
-
- >>> re.findall("a{2}","aaaaaaaa")
- ['aa', 'aa', 'aa', 'aa']
-
- {m,n}? 用来表示前面正则表达式的m到n次copy,尝试匹配尽可能少的copy
-
- >>> re.findall("a{2,4}?","aaaaaaaa")
- ['aa', 'aa', 'aa', 'aa']
-
- 10。元字符( "( )" ),用来表示一个group的开始和结束。
-
- 比较常用的有(REs),(?P<name>REs),这是无名称的组和有名称的group,有名称的group,可以通过matchObject.group(name)
-
- 获取匹配的group,而无名称的group可以通过从1开始的group序号来获取匹配的组,如matchObject.group(1)。具体应用将在下面的group()方法中举例讲解
-
-
-
- 11.元字符(.)
-
- 元字符“.”在默认模式下,匹配除换行符外的所有字符。在DOTALL模式下,匹配所有字符,包括换行符。
-
- >>> import re
-
- >>> re.match(".","\n")
-
- >>> m=re.match(".","\n")
-
- >>> print m
-
- None
-
- >>> m=re.match(".","\n",re.DOTALL)
-
- >>> print m
-
- <_sre.SRE_Match object at 0x00C2CE20>
-
- >>> m.group()
-
- '\n'
-
-
-
- 下面我们首先来看一下Match Object对象拥有的方法,下面是常用的几个方法的简单介绍
-
- 1.group([group1,…])
-
- 返回匹配到的一个或者多个子组。如果是一个参数,那么结果就是一个字符串,如果是多个参数,那么结果就是一个参数一个item的元组。group1的默认值为0(将返回所有的匹配值).如果groupN参数为0,相对应的返回值就是全部匹配的字符串,如果group1的值是[1…99]范围之内的,那么将匹配对应括号组的字符串。如果组号是负的或者比pattern中定义的组号大,那么将抛出IndexError异常。如果pattern没有匹配到,但是group匹配到了,那么group的值也为None。如果一个pattern可以匹配多个,那么组对应的是样式匹配的最后一个。另外,子组是根据括号从左向右来进行区分的。
-
- >>> m=re.match("(\w+) (\w+)","abcd efgh, chaj")
-
- >>> m.group() # 匹配全部
-
- 'abcd efgh'
-
- >>> m.group(1) # 第一个括号的子组.
-
- 'abcd'
-
- >>> m.group(2)
-
- 'efgh'
-
- >>> m.group(1,2) # 多个参数返回一个元组
-
- ('abcd', 'efgh')
-
- >>> m=re.match("(?P<first_name>\w+) (?P<last_name>\w+)","sam lee")
- >>> m.group("first_name") #使用group获取含有name的子组
- 'sam'
- >>> m.group("last_name")
- 'lee'
-
-
-
- 下面把括号去掉
-
- >>> m=re.match("\w+ \w+","abcd efgh, chaj")
-
- >>> m.group()
-
- 'abcd efgh'
-
- >>> m.group(1)
-
- Traceback (most recent call last):
-
- File "<pyshell#32>", line 1, in <module>
-
- m.group(1)
-
- IndexError: no such group
-
-
-
- If a group matches multiple times, only the last match is accessible:
-
- 如果一个组匹配多个,那么仅仅返回匹配的最后一个的。
-
- >>> m=re.match(r"(..)+","a1b2c3")
-
- >>> m.group(1)
-
- 'c3'
-
- >>> m.group()
-
- 'a1b2c3'
-
- Group的默认值为0,返回正则表达式pattern匹配到的字符串
-
-
-
- >>> s="afkak1aafal12345adadsfa"
-
- >>> pattern=r"(\d)\w+(\d{2})\w"
-
- >>> m=re.match(pattern,s)
-
- >>> print m
-
- None
-
- >>> m=re.search(pattern,s)
-
- >>> m
-
- <_sre.SRE_Match object at 0x00C2FDA0>
-
- >>> m.group()
-
- '1aafal12345a'
-
- >>> m.group(1)
-
- '1'
-
- >>> m.group(2)
-
- '45'
-
- >>> m.group(1,2,0)
-
- ('1', '45', '1aafal12345a')
-
-
-
- 2。groups([default])
-
- 返回一个包含所有子组的元组。Default是用来设置没有匹配到组的默认值的。Default默认是"None”,
-
- >>> m=re.match("(\d+)\.(\d+)","23.123")
-
- >>> m.groups()
-
- ('23', '123')
-
- >>> m=re.match("(\d+)\.?(\d+)?","24") #这里的第二个\d没有匹配到,使用默认值"None"
-
- >>> m.groups()
-
- ('24', None)
-
- >>> m.groups("0")
-
- ('24', '0')
-
-
-
- 3.groupdict([default])
-
- 返回匹配到的所有命名子组的字典。Key是name值,value是匹配到的值。参数default是没有匹配到的子组的默认值。这里与groups()方法的参数是一样的。默认值为None
-
- >>> m=re.match("(\w+) (\w+)","hello world")
-
- >>> m.groupdict()
-
- {}
-
- >>> m=re.match("(?P<first>\w+) (?P<secode>\w+)","hello world")
-
- >>> m.groupdict()
-
- {'secode': 'world', 'first': 'hello'}
-
- 通过上例可以看出,groupdict()对没有name的子组不起作用
-
-
-
-
-
- 正则表达式对象
-
- re.search(string[, pos[, endpos]])
-
- 扫描字符串string,查找与正则表达式匹配的位置。如果找到一个匹配就返回一个MatchObject对象(并不会匹配所有的)。如果没有找到那么返回None。
-
- 第二个参数表示从字符串的那个位置开始,默认是0
-
- 第三个参数endpos限定字符串最远被查找到哪里。默认值就是字符串的长度。.
-
- >>> m=re.search("abcd", '1abcd2abcd')
- >>> m.group() #找到即返回一个match object,然后根据该对象的方法,查找匹配到的结果。
- 'abcd'
- >>> m.start()
- 1
- >>> m.end()
- 5
-
- >>> re.findall("abcd","1abcd2abcd")
- ['abcd', 'abcd']
-
-
-
- re.split(pattern, string[, maxsplit=0, flags=0])
-
- 用pattern来拆分string。如果pattern有含有括号,那么在pattern中所有的组也会返回。
-
- >>> re.split("\W+","words,words,works",1)
-
- ['words', 'words,works']
-
- >>> re.split("[a-z]","0A3b9z",re.IGNORECASE)
-
- ['0A3', '9', '']
-
- >>> re.split("[a-z]+","0A3b9z",re.IGNORECASE)
-
- ['0A3', '9', '']
-
- >>> re.split("[a-zA-Z]+","0A3b9z")
-
- ['0', '3', '9', '']
-
- >>> re.split('[a-f]+', '0a3B9', re.IGNORECASE)#re.IGNORECASE用来忽略pattern中的大小写。
-
- ['0', '3B9']
-
-
-
- 如果在split的时候捕获了组,并且匹配字符串的开始,那么返回的结果将会以一个空串开始。
-
- >>> re.split('(\W+)', '...words, words...')
-
- ['', '...', 'words', ', ', 'words', '...', '']
-
- >>> re.split('(\W+)', 'words, words...')
-
- ['words', ', ', 'words', '...', '']
-
-
-
- re.findall(pattern, string[, flags])
-
- 以list的形式返回string中所有与pattern匹配的不重叠的字符串。String从左向右扫描,匹配的返回结果也是以这个顺序。
-
- Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
-
- >>> re.findall('(\W+)', 'words, words...')
-
- [', ', '...']
-
- >>> re.findall('(\W+)d', 'words, words...d')
-
- ['...']
-
- >>> re.findall('(\W+)d', '...dwords, words...d')
-
- ['...', '...']
-
-
-
- re.finditer(pattern, string[, flags])
-
- 与findall类似,只不过是返回list,而是返回了一个叠代器
-
-
-
- 我们来看一个sub和subn的例子
-
- >>> re.sub("\d","abc1def2hijk","RE")
-
- 'RE'
-
- >>> x=re.sub("\d","abc1def2hijk","RE")
-
- >>> x
-
- 'RE'
-
- >>> re.sub("\d","RE","abc1def2hijk",)
-
- 'abcREdefREhijk'
-
-
-
- >>> re.subn("\d","RE","abc1def2hijk",)
-
- ('abcREdefREhijk', 2)
-
- 通过例子我们可以看出sub和subn的差别:sub返回替换后的字符串,而subn返回由替换后的字符串以及替换的个数组成的元组。
-
- re.sub(pattern, repl, string[, count, flags])
-
- 用repl替换字符串string中的pattern。如果pattern没有匹配到,那么返回的字符串没有变化]。Repl可以是一个字符串,也可以是一个function。如果是字符串,如果repl是个方法/函数。对于所有的pattern匹配到。他都回调用这个方法/函数。这个函数和方法使用单个match object作为参数,然后返回替换后的字符串。下面是官网提供的例子:
-
- >>> def dashrepl(matchobj):... if matchobj.group(0) == '-': return ' '... else: retu
|