开发者

python regular expression help

开发者 https://www.devze.com 2023-01-30 02:04 出处:网络
Need to match any string ends up with a letter, and the second last character i开发者_StackOverflow中文版s \'>\'

Need to match any string ends up with a letter, and the second last character i开发者_StackOverflow中文版s '>'

It will match:

abc>a
ddd_4>f

It will not match:

abc>ab
abc>2


>>> import re
>>> s = 'abc>a'
>>> r = re.compile(r'>[:alpha:]$')
>>> print( r.search(s) )
<_sre.SRE_Match object at 0xb76c5a30>
>>> 

If you want to match letters according to locales.


re.compile(r'.*>[a-zA-Z]$')

should generate the pattern that you want.

However, I recommend that you take a read through the regexp part of Google's Python class. Then you can learn how to do things like this yourself.


.*>[a-zA-Z]$

>>> for s in ('abc>a', 'ddd_4>f', 'abc>ab', 'abc>2'):
...     print re.match(r'.*>[a-zA-Z]$', s)
... 
<_sre.SRE_Match object at 0xb7217e58>
<_sre.SRE_Match object at 0xb7217e58>
None
None


I think this is what you are looking for:

import re 
re.search(">[a-zA-Z]$", str)

It will evaluate to None if the string does not match.

0

精彩评论

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