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

2024-09-29 17:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

列表是a = ['Aeroplane','Ramanujan','World-king','Pizza/Burger'] 我试图用Pizza_BurgerWorld_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)

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


Tags: retxt列表worldargresppburger
1条回答
网友
1楼 · 发布于 2024-09-29 17:18:34

清理术语的一个简单方法是循环遍历术语并分别清理每个术语。你可以做一些简单的事情,比如'World-king'.replace('/','_').replace('-','_')

或者可以使用regex进行如下清理:

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

相关问题 更多 >

    热门问题