Skip to main content
 首页 » 编程设计

Python 正则表达式搜索并替换所有出现的地方

2024年10月01日28jyk

我希望你能帮我解决这个问题。我正在用 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. 

请您参考如下方法:

作为 sub 的文档方法说:

Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.

所以,改成这样:

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>