在 python 中搜索字母数字字符并将其替换为空字符串

Search and replace alphanumeric characters with empty string in python

如果此 post 重复,我深表歉意。我试图用import repythonsearch/replace一个词。在下面的示例中,我只想找到 aaa1 并将其替换为 empty string.

# Input case 1
str = 'aaa,aaa1,aaa1.1'

# Input case 2
str = 'aaa,aaa1'

# Expected output for the case 1
'aaa,aaa1.1'

# Expected output for the case 2
'aaa'

我尝试了单词边界 \b,老实说,我对它是什么以及如何正确使用它感到困惑 (https://www.regular-expressions.info/wordboundaries.html)。

re.sub(r'\baaa1\b', '', str)

结果是 aaa,,.1 正如你们中的一些人已经预料的那样。我也尝试过 /^aaa1$/ 但没有运气。我是 python 及其模块(例如 re)的新手。我很感激你关于如何拉 ^ objective.

的建议

[更新]

我用输入和预期输出更新了我的原始问题,以澄清我的 objective。

这样做就可以了:

def f(str):
    s = str.split(',')
    if 'aaa1' in s:
        for n in s:
            if n == 'aaa1': s.remove(n)
        return(','.join(s))
    else:
        for n in s:
            if 'aaa1' in n: s.remove(n)
        return(','.join(s))

print(f('aaa,aaa1,aaa1.1'))
print(f('aaa,aaa1.1'))

输出:

aaa,aaa1.1
aaa

给你:

def filter_str(s):
    s = re.sub(r'\baaa1,', '', s)
    return re.sub(r',aaa1$', '', s)