【问题标题】:How to replace and lowercase 2 or more groups using re in python如何在python中使用re替换和小写2个或更多组
【发布时间】:2013-06-05 01:04:17
【问题描述】:

我正在尝试将一些大写的 bbcode 标签替换为小写,如下所示:

p=re.compile(r'\[URL="(.*?)"\](.*?)\[/URL\]',re.S+re.I)
message=p.sub('[url=\\1]\\2[/url]',message)

但我需要替换大量标签,所以我不会为每个标签进行编译。如果我使用 [(.*?)],则 sub 将替换为相同的大写字母。

所以问题是:

如何在 Python 中使用 RE 替换和小写 2 个或多个组

【问题讨论】:

    标签: python regex


    【解决方案1】:

    那么,我从这里开始使用简单的方法进行 1 组:

    Using a regular expression to replace upper case repeated letters in python with a single lowercase letter

    text='dsads [QUOTE]test[/QUOTE]<br><br>[URL=http://test.com]what[/URL] dsadkd [B]TEST[/B]'
    
    def replacement(match):
      return "["+match.group(1).lower()+"]"
    
    >>> re.sub(r'\[(.*?)\]', replacement, text)
    RESULT: 'dsads [quote]test[/quote]<br><br>[url=http://test.com]what[/url] dsadkd [b]TEST[/b]'
    

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 2017-09-23
      • 1970-01-01
      • 2011-11-25
      • 2022-09-30
      • 2021-09-24
      • 1970-01-01
      • 2015-10-31
      • 2021-12-16
      相关资源
      最近更新 更多