20121020 Google python课堂 正则表达式

match = re.search(pat, str)输入正则表达式与字符串,如果找到返回匹配的对象,否则None,通常可以用if来判断是否找到
match.group()返回匹配成功的文本
match = re.search(r'pat', str)正则表达式前的r表示'raw'保持原始的字符串,对\转意忽略
 
正则表达式
A, X, 9, <    普通字符完全匹配
.             匹配任何字符,除了'\n'
\w            匹配字符,\W匹配飞、非字符
\b            字符与字符之间的边界
\s            匹配空白符,空格 \n\r\t\f等,\S匹配非空白符
\t,\n,\r      制表符,回车符,返回
\d            数字,\w,\S包含
^,$           字符串的开始与结束
\             转意字符
 
重复的标识
+     字符左边相同的字符
*     匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。 * 等价于{0,}。
?     匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 中的"do" 。? 等价于 {0,1}。
 
[ xyz]  字符集合。匹配所包含的任意一个字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。
[^ xyz] 负值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的'p'。
 
分组提取
1 str ='purple [email protected] monkey dishwasher'

2 match = re.search('([\w.-]+)@([\w.-]+)', str)

3 if match:

4     print match.group()   ## '[email protected]' (the whole match)

5     print match.group(1)  ## 'alice-b' (the username, group 1)

6     print match.group(2)  ## 'google.com' (the host, group 2)

用()区分各个分组

 
re.findall(pat, str)
找到所有与正则表示的符合的各个字符串,返回一个有这些字符串为元的表
findall与()可以组合使用,返回数组为元的表
 
正则表达式的选项
re.search(pat, str, re.IGNORECASE)
IGNORECASE 不区分大小写a,即匹配a,又匹配A
DOTALL     允许.匹配\n
MULTILINE  在一个多行组成的字符串中,允许^与$匹配行的开始于结束
 
re.sub(pat, replacement, str) 替换匹配到的字符串
1 str ='purple [email protected], blah monkey [email protected] blah dishwasher'

2 ## re.sub(pat, replacement, str) -- returns new string with all replacements,

3 ## \1 is group(1), \2 group(2) in the replacement

4 print re.sub(r'([\w\.-]+)@([\w\.-]+)', r'\[email protected]', str)

5 ## purple [email protected], blah monkey [email protected] blah dishwasher

你可能感兴趣的:(python)