Skip to main content
 首页 » 编程设计

python之正则表达式未在 python 中返回预期的输出

2025年05月04日26mfrbuaa

列表是a = ['Aeroplane','Ramanujan','World-king','Pizza/Burger'] 我正在尝试用 Pizza_Burger 和 World_king 替换列表中的项目(使用 -, /)。无论符号是什么,都应替换为下划线。

这是我的代码:

import re 
def replaceStrings(arg): 
    txt =arg 
    res = re.search(r'(?i)\b([a-z][a-z0-9_]*)([/-]+)([a-z][a-z0-9_]*)\b', txt) 
    if res: 
        pp = reg.sub(r'\1_\2',txt) 
        print(pp) 
        return pp 
 
 
 
for i in a: 
    replaceStrings(i) 

但是我没有得到想要的输出。我的正则表达式有什么问题。 我是正则表达式的初学者。谢谢

请您参考如下方法:

清理术语的一种简单方法是遍历这些术语并分别清理每个术语。你可以只做一些像 'World-king'.replace('/','_').replace('-','_')

这样简单的事情

或者您可以像这样使用正则表达式进行清理:

import re 
def replaceStrings(arg): 
    # each individual special character you want to clean can be put in the brackets `[]` 
    pp = re.sub(r'[-/]', '_', arg) 
    print(pp) 
    return pp 
 
 
a = ['Aeroplane','Ramanujan','World-king','Pizza/Burger'] 
for i in a: 
    replaceStrings(i) 

输出:

Aeroplane 
Ramanujan 
World_king 
Pizza_Burger 

更新:[OP 添加的评论]

I took a precautionary measure making sure I have the string of the required pattern. My question is, Is it a good practice The way I wrote an extra step instead of directly doing re.sub?

如果你想在清理模式之前确保模式匹配,也可以这样做:

import re 
 
pattern = re.compile(r'(?i)\b([a-z][a-z0-9_]*)([/-]+)([a-z][a-z0-9_]*)\b') 
 
def replaceStrings(arg): 
    if pattern.match(arg): 
        pp = re.sub(r'[-/]','_', arg) 
        print(pp) 
        return pp 
 
a = ['Aeroplane','Ramanujan','World-king','Pizza/Burger'] 
for i in a: 
    replaceStrings(i) 

输出:

World_king 
Pizza_Burger