如何将Perl正则表达式转换为Python?

时间:2015-10-05 17:28:18

标签: python regex perl python-3.x

如何将此Perl正则表达式转换为Python:

(?:

    ^(?:never|no|nothing|nowhere|noone|none|not|
        havent|hasnt|hadnt|cant|couldnt|shouldnt|
        wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
    )$

)

|

n't

1 个答案:

答案 0 :(得分:4)

该表达式在Python中与一样。只需使用re.VERBOSE switch或删除所有空格。

演示:

>>> import re
>>> pattern = re.compile('''\
... (?:
... 
...     ^(?:never|no|nothing|nowhere|noone|none|not|
...         havent|hasnt|hadnt|cant|couldnt|shouldnt|
...         wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
...     )$
... 
... )
... 
... |
... 
... n't
... ''', flags=re.VERBOSE)
>>> pattern.match('never').group()
'never'
>>> pattern.match('wouldnt').group()
'wouldnt'