Regular expression: match start or whitespace

前端 未结 8 1590
无人共我
无人共我 2020-11-29 06:32

Can a regular expression match whitespace or the start of a string?

I\'m trying to replace currency the abbreviation GBP with a £ symbol. I

相关标签:
8条回答
  • 2020-11-29 07:03

    Use the OR "|" operator:

    >>> re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text)
    u'\xa3 5 Off when you spend \xa375.00'
    
    0 讨论(0)
  • 2020-11-29 07:03

    Yes, why not?

    re.sub(u'^\W*GBP...
    

    matches the start of the string, 0 or more whitespaces, then GBP...

    edit: Oh, I think you want alternation, use the |:

    re.sub(u'(^|\W)GBP...
    
    0 讨论(0)
提交回复
热议问题