简单的正则表达式python实现 发表于 2017-03-08 | 分类于 python 简单的Python实现正则表达式,对文字的分析用的多,爬虫也会用到。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import restr = 'dog cat dog'r_str = r'dog'match = re.match(r_str,str)print match.group(0)#dogmatch = re.search(r_str,str)print match.group(0)#dogprint match.start()#0print match.end()#3List = re.findall(r_str,str)print List#['dog', 'dog']contactInfo = 'Doe, John: 555-1212'r_str = r'\w+, \w+: \S+'match = re.search(r_str,contactInfo)print match.group(0)#Doe, John: 555-1212r_group_str = r'(\w+), (\w+): (\S+)'match = re.search(r_group_str,contactInfo)print match.group(0)#Doe, John: 555-1212print match.group(1)#Doeprint match.group(2)#Johnprint match.group(3)#555-1212r_group_name_str = r'(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+)'match = re.search(r_group_name_str,contactInfo)print match.group('last')#Doeprint match.group('first')#Johnprint match.group('phone')#555-1212List = re.findall(r_group_str,contactInfo)print List#[('Doe', 'John', '555-1212')]