我想要做的是擺脫星號之間的數字并保留其他數字。我運行我的正則運算式,但它洗掉了asterics之間的所有內容。
import re
msg = """
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon 16 pieces * ($ 44.50 MXN)
1 x * Potatoes 220 g * ($ 44.50 MXN) """
re.sub(r'\*.*\*', "", msg)
我正在尋找的預期結果是:
"""
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon pieces * ($ 44.50 MXN)
1 x * Potatoes g * ($ 44.50 MXN)
"""
uj5u.com熱心網友回復:
您可以將 a 傳遞lambda給 re.sub forrepl并過濾掉星號內包含的子字串的數字:
result = re.sub('\*. \*',
lambda x: ''.join(c for c in x.group(0) if not c.isdigit()),
msg)
print(result)
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamon pieces * ($ 44.50 MXN)
1 x * Potatoes g * ($ 44.50 MXN)
re.sub如果您不想使用上述方法(不會洗掉前面/后面的空格字符),則可以使用嵌套:
result = re.sub('\*. \*',
lambda x: re.sub('\s*\d \s*','',x.group(0)),
msg)
print(result)
1 x * Build your pizza * ($ 99MXN)
1 x * Baitz Cinnamonpieces * ($ 44.50 MXN)
1 x * Potatoesg * ($ 44.50 MXN)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354303.html
上一篇:從制表符分隔的檔案中提取數字
下一篇:匹配組后跟不同結尾的組
