分类: Python/Ruby
2010-01-07 10:26:42
正则表达式
具体内容参考手册,这里记下一些小问题:
1、re对象的方法
match Match a regular expression pattern to the beginning of a string.
search re.search(pattern, string, flags) flags:re.I re.M re.X re.S re.L re.U
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
|
re对象的使用方法,reobject = re.complie(pattern),从reobject获得pattern的方法,使用reobject.pattern属性
如果一个reobject要多次使用,最好使用compile方法提高性能,否则可以直接按这种方式使用,re.search(pattern, string)
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
2、要使group(s)方法,应该在pattern中对想要在tuples中的部分加上括号,例如“123-45”,想匹配这个string,但是只想获得前三个数字,则可以使用这样的pattern,"(\d{3})-\d{2}" ,注意前面使用了括号,再调用groups方法会得到tuples,("123",) 。group(s)是SRE_Match object 的方法,通常使用方法为reobject.search(string).group(s)
3、要匹配任意单个字符使用".",任意个字符使用".*"(包括0个),或者".+"(至少一个)。
4、括号的多种用法
(?:)不放入groups中
(?iLmsux) 为pattern加入I,L,M,S,U,X标志
(?P
(?P=name) 匹配在之前用name表示的部分表达式所匹配到的内容
(?#comment) 注释
test1(?=test2) 如果test1后面跟着test2,则匹配test1
test1(?!test2) 如果test1后面跟着的不是test2,则匹配test1
(?<=test1)test2 如果test2前面匹配到test1,则将test2放入group
(?
(?(id/name)yes-pattern|no-pattern) 如果id/name所指的项匹配到了,则执行yes,否则执行no
5、特殊序列
\b 匹配空字符,比如\bare\b匹配完整的单词are,\bare匹配在单词开头的are,而are\b则匹配在单词结尾的are
\B 与\b相反,\Bare匹配不在单词开头的are,而are\B匹配不在单词结尾的are
\d 匹配任何数字,相当于class [0-9]。
\D 匹配任何非数字,相当于class [^0-9]。
\s 匹配任何空白,相当于class [ \t\n\r\f\v]。
\S 匹配任何非空白,相当于class [^ \t\n\r\f\v]。
\w 匹配任何或数字,相当于class [a-zA-Z0-9_]。如果定义了re.L标志,则还包括当前LOCALE的一些字符。
\W 匹配\w的补集。
\\ 匹配反斜杠。
6、匹配后返回的对象的start()和end()方法,参数为组ID,返回值分别为匹配到的子字符串的开头和结尾在原字符串中的index。
问题1:如何匹配不在开头的一个substring,如"2341254",要匹配"254"而不是开头的"234"
解决方法:re.search("(?<=.)2.4", s),同样要匹配不在结尾的一个substring,可以这样re.search("2.4(?=.)", s)