how to right the regular expression ?

MRAB python at mrabarnett.plus.com
Thu Feb 14 16:43:42 CET 2013


On 2013-02-14 14:13, python wrote:
> my tv.txt is :
> http://202.177.192.119/radio5 香港电台第五台(可于Totem/VLC/MPlayer播放)
> http://202.177.192.119/radio35 香港电台第五台(DAB版,可于Totem/VLC/MPlayer播放)
> http://202.177.192.119/radiopth 香港电台普通话台(可于Totem/VLC/MPlayer播放)
> http://202.177.192.119/radio31 香港电台普通话台(DAB版,可于Totem/VLC/MPlayer播放)
> octoshape:rthk.ch1 香港电台第一台(粤)
> octoshape:rthk.ch2 香港电台第二台(粤)
> octoshape:rthk.ch6 香港电台普通话台
> octoshape:rthk.ch3 香港电台第三台(英)
>
> what i want to get the result is
> 1group is  http://202.177.192.119/radio5  2group is  香港电台第五台  3group is  (可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radio35  2group is  香港电台第五台  3group is  (DAB版,可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radiopth  2group is  香港电台普通话台  3group is  (可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radio31  2group is  香港电台普通话台  3group is  (DAB版,可于Totem/VLC/MPlayer播放)
> 1group is  octoshape:rthk.ch1  2group is  香港电台第一台 3group is  (粤)
> 1group is  octoshape:rthk.ch2  2group is  香港电台第二台 3group is  (粤)
> 1group is  octoshape:rthk.ch6  2group is  香港电台普通话台 3group is  none
> 1group is  octoshape:rthk.ch3  2group is  香港电台第三台 3group is  (英)
 >
> here is my code:
> # -*- coding: utf-8 -*-
> import re
> rfile=open("tv.txt","r")
> pat='([a-z].+?\s)(.+)(\(.+\))'
> for  line in  rfile.readlines():
>      Match=re.match(pat,line)
>      print "1group is ",Match.group(1),"2group is
> ",Match.group(2),"3group is ",Match.group(3)
> rfile.close()
>
> the output is :
> 1group is  http://202.177.192.119/radio5  2group is  香港电台第五台
> 3group is  (可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radio35  2group is  香港电台第五台
> 3group is  (DAB版,可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radiopth  2group is  香港电台普通话台
> 3group is  (可于Totem/VLC/MPlayer播放)
> 1group is  http://202.177.192.119/radio31  2group is  香港电台普通话台
> 3group is  (DAB版,可于Totem/VLC/MPlayer播放)
> 1group is  octoshape:rthk.ch1  2group is  香港电台第一台 3group is  (粤)
> 1group is  octoshape:rthk.ch2  2group is  香港电台第二台 3group is  (粤)
> 1group is
> Traceback (most recent call last):
>    File "tv.py", line 7, in <module>
>      print "1group is ",Match.group(1),"2group is ",Match.group(2),"3group is ",Match.group(3)
> AttributeError: 'NoneType' object has no attribute 'group'
>
> how to revise my code to get the output?
>
The problem is that the regex makes '(\(.+\))' mandatory, but example 7
doesn't match it.

You can make it optional by wrapping it in a non-capturing group
(?:...), like this:

pat = r'([a-z].+?\s)(.+)(?:(\(.+\)))?'

Also, it's highly recommended that you use raw string literals
(r'...') when writing regex patterns and replacements.




More information about the Python-list mailing list