【问题标题】:Python regex search and replace all ocurrencesPython正则表达式搜索并替换所有出现
【发布时间】:2017-08-03 04:16:36
【问题描述】:

我希望你能帮助我解决这个问题。我正在用 python 编写代码来替换字符串上的所有匹配项,其中包括:@[username](user:id)

我尝试使用以下代码,但仅在我的字符串是这样的情况下才有效:

mystring = '@[otheruser](id: 100)' and match and replace it's ok. But if I pass a string like this:

mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)' doesn't work, nothing gets replaced.

代码:

import re

mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)'

regex = re.compile(r'^@\[([a-zA-Z0-9]+)\]\((id: ([0-9]+))\)', re.S)
iter = re.finditer(regex, mystring)

    for result in iter:
        match = result.group()
        g1 = result.group(1)
        g2 = result.group(2)
        g3 = result.group(3)

        print(match) # full match
        print(g1) # otheruser
        print(g2) # id: number_id
        print(g3)  # number_id

        parsed_string = re.sub(p, '<a href="view/'+g3+'">@'+g1+'</a>' , mystring)

输出应该类似于:

He is <a href="view/100">@otheruser</a> and he is <a href="view/20">@newuser</a> doesn't work, nothing gets replaced.

【问题讨论】:

  • 这个是markdown语法吗?

标签: python regex django


【解决方案1】:

正如sub 方法的文档所说:

反向引用,例如 \6,被替换为模式中第 6 组匹配的子字符串。

所以,改成这样:

import re

mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)'
my_re = r'@\[([a-zA-Z0-9]+)\]\((id: ([0-9]+))\)'  # note the missing ^ at start

regex = re.compile(my_re, re.S)
iter = re.finditer(regex, mystring)

for result in iter:
    match = result.group()
    g1 = result.group(1)
    g2 = result.group(2)
    g3 = result.group(3)

    print(match) # full match
    print(g1) # otheruser
    print(g2) # id: number_id
    print(g3)  # number_id

    # we make use of \1 to match the first matched group (which is the number_id 
    # and \3 which is the username
    parsed_string = re.sub(my_re, 
                           r'<a href="view/\3">@\1</a>', 
                           mystring)
    print(parsed_string)
    # prints
    # He is <a href="view/100">@otheruser</a> and he is <a href="view/20">@newuser</a>

【讨论】:

  • 太棒了,感谢您的帮助,效果很好,我想我误解了^的使用
  • @ElrosRomeo。如果我的回答帮助您解决了您的问题,请采纳。这是 StackOverflow 中的一个好习惯。另外,如果你真的喜欢它,也请点赞:)
【解决方案2】:

我不知道你的代码做了什么,但是使用 re 替换 python 中的字符串就像这样简单:

import re

mystring = 'He is @[otheruser](id: 100) and he is @[newuser](id: 20)'
regex = re.compile(r'@\[(\w+)\]\(id\:\s(\d+)\)', re.I)
r_p = r'<a href="view/\2">@\1</a>'
print(regex.sub(p, mystring))

请注意我删除了^(插入符号),因为它表示字符串的开头,而您的情况并非如此。 https://regex101.com/r/fUztdt/1

【讨论】:

  • re 下的大多数函数都适用于字符串或已编译的模式对象。
  • 我的错。感谢您的澄清。
  • 也感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-07-25
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 2022-06-10
  • 2013-06-19
相关资源
最近更新 更多