【问题标题】:Python re question - sub challengePython 重新提问 - 子挑战
【发布时间】:2009-08-19 14:27:28
【问题描述】:

我想为所有以 # 或 ! 为前缀的单词添加 href 链接或者 @ 如果这是文字

查看#bamboo 并联系@Fred re #bamboo #garden

应转换为:

Check the <a href="/what/bamboo">#bamboo</a> and contact <a href="/who/fred">@Fred</a> re <a href="/what/bamboo">#bamboo</a> <a href="/what/garden">#garden</a>

注意#和@去不同的地方。

据我所知,只是做哈希......

matched = re.sub("[#](?P<keyword>\w+)", \
    '<a href="/what/(?P=keyword)">(?P=keyword)</a>', \
    text)

任何能够为我指明正确方向的专家。我需要为每个符号做单独的匹配吗?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    我会用一个匹配和一个选择“地点”的函数来完成。即:

    import re
    
    places = {'#': 'what',
              '@': 'who',
              '!': 'why',
             }
    
    def replace(m):
      all = m.group(0)
      first, rest = all[0], all[1:]
      return '<a href="/%s/%s">%s</a>' % (
        places[first], rest, all)
    
    markedup = re.sub(r'[#!@]\w+', replace, text)
    

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多