在 Python 中使用正则表达式摆脱星号“*”内的数字
Get rid of just the numers inside asterics "*" using regex in Python
我想做的是去掉星号之间的数字并保留其他数字。我 运行 我的正则表达式,但它删除了 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)
"""
您可以将 lambda
传递给 re.sub 以获得 repl
并过滤掉包含在星号内的子字符串的数字:
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
(不会删除 preceding/following 白色 space 字符):
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)
我想做的是去掉星号之间的数字并保留其他数字。我 运行 我的正则表达式,但它删除了 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)
"""
您可以将 lambda
传递给 re.sub 以获得 repl
并过滤掉包含在星号内的子字符串的数字:
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
(不会删除 preceding/following 白色 space 字符):
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)