开发者

Regular expressions split and match

开发者 https://www.devze.com 2023-01-13 01:49 出处:网络
>>> zznew \'...0002211 118 7.5 \"Weeds\" (2005) {The Love Circle Overlap (#4.10)}\' >>> re.split(\'\\(+\\d+\\)\',z开发者_开发技巧znew)
>>> zznew
'...0002211 118 7.5 "Weeds" (2005) {The Love Circle Overlap (#4.10)}'

>>> re.split('\(+\d+\)',z开发者_开发技巧znew)
['...0002211 118 7.5 "Weeds" ', ' {The Love Circle Overlap (#4.10)}']

>>> m = re.match('\(+\d+\)',zznew)

>>> m.groups()
Traceback (most recent call last):
  File "<pyshell#104>", line 1, in <module>
    m.groups()
AttributeError: 'NoneType' object has no attribute 'groups'

in the above example when i use split it matches with (2005) and splits it... but when i use match its not match...the m.groups() file is empty.. what is wrong with this :(


Use re.search instead of re.match.

The difference between these two methods is that re.match only matches if the match starts at the beginning of the string, whereas re.search can match anywhere in the string. See the documentation for more details.

As NullUserException points out, if you want to extract the year you can do it as follows:

m = re.search('\((\d+)\)', zznew)
print m.group(1)
0

精彩评论

暂无评论...
验证码 换一张
取 消