删除除十进制数字外的所有字符,其后立即加上£符号

时间:2018-12-13 22:19:44

标签: python regex

我的文字的值如下:

this is a value £28.99 (0.28/ml)

我想删除所有内容以仅返回价格,以便返回:

£28.99

£和。之间可以有任意数字。

思考

r"£[0-9]*\.[0-9]{2}"

与我要保留的模式匹配,但是我不确定如何删除其他所有内容并保留该模式,而不是像通常的re.sub()情况那样替换该模式。

4 个答案:

答案 0 :(得分:2)

您不在乎小数点前有多少个数字,因此使用零个或多个匹配器是正确的。但是,您可以仅依靠数字类(\d)来提供更简洁的信息。

小数点后也是如此。您只需要两个即可,将匹配项限制为2个是正确的。

然后问题出在如何真正捕获值上。您可以使用一个捕获组来确保仅获得您所关心的价值。

完整的正则表达式:

(£\d*.\d{2})

示例代码:

import re
r = re.compile("(£\d*.\d{2})")
match = r.findall("this is a value £28.99 (0.28/ml)")
if match: # may bring back an empty list; check for that here
    print(match[0]) # uses the first group, and will print £28.99

答案 1 :(得分:2)

  

我想删除所有内容以仅返回价格,以便返回:

为什么不尝试提取正确的信息呢?

import re

s = "this is a value £28.99 (0.28/ml)"

m = re.search("£\d*(\.\d+)?",s)
if m:
   print(m.group(0))

要查找多个事件,请使用findallfinditer而不是search

答案 2 :(得分:2)

如果是字符串,则可以执行以下操作:

x = "this is a value £28.99 (0.28/ml)"
x_list = x.split()
for i in x_list:
    if "£" in i: #or if i.startswith("£") Credit – Jean-François Fabre
        value=i
print(value)
>>>£28.99

答案 3 :(得分:-2)

您可以尝试:

import re
t = "this is a value £28.99 (0.28/ml)"
r = re.sub(".*(£[\d.]+).*", r"\1", t)
print(r)

输出:

£28.99

Python Demo