Python正则表达式一

推荐

http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html#!comments

这篇博客超好,建议收藏。

不过对于正则表达式小白,他没有说到strRe = r'(\d+)\D+(\d+)' #编写的正则表达式()表示一个匹配的对象有几个(),匹配结果元组中有几项,可以二维数组理解

Python正则表达式的使用

使用方法一:将正则表达式字符串--》正则表达式对象Pattern--》匹配的结果Match

1 strRe = "hello" #编写的正则表达式
2 strSour = "hello world!"#被匹配的字符串
3 pattern = re.compile(strRe)#编译为Pattern对象
4 match = pattern.match(strSour)#将匹配结果存储到Pattern对象中
5 if match:
6     print(match.group())
7     #输出:hello

使用方法二:

 1 #! /bin/env python
 2 # -*- coding: utf-8 -*-
 3 import re
 4 
 5 strRe = r'(\d+)\D+(\d+)' #编写的正则表达式()表示一个匹配的对象有几个(),匹配结果元组中有几项,可以二维数组理解
 6 strSour = "one1two2three3four4"#被匹配的字符串
 7 m = re.findall(strRe, strSour)#m为Match对象
 8 if len(m)>0:
 9     for i in range(0,len(m)):
10         print(m[i][0])
11         print(m[i][1])
12 # 输出:1
13 #      2
14 #      3
15 #      4

 

推挤使用方法二。可以将匹配结果存储到多维数组中。从而提取结果。验证的话只要证明len(m)<=0

posted @ 2014-12-26 17:24  moye  阅读(170)  评论(0编辑  收藏  举报