正则表示欧元英镑和美元的价格

时间:2015-07-09 16:54:47

标签: python regex unicode

我正在使用python正则表达式查找字符串中的所有价格。到目前为止,我只是无法正确管理符号。 此代码的输入为:'happy$37.54000happy$34$3454$3333€27.80€3.00.33.2£27.000'

   import sys
   import re
   price = sys.argv[1]
   new = re.findall(r'[\$\20AC\00A3]{1}\d+\.?\d{0,2}',price,re.UNICODE)
   for prices in new:
       print prices

OUPUTS:

$37.54
$34
$3454    
$3333

我想要的是:

$37.54
$34
$3454
$3333
€27.80
€3.00    
£27.00

如果我将欧元符号添加到代码中,则文件无法编译,因为它不是unicode字符。我在想,因为20AC是欧元符号的unicode,而\00A3是英镑符号的unicode,它会起作用,但事实并非如此。

我认为问题在于这部分代码:...

[\$\20AC\00A3]...

非常感谢任何帮助

为未来人士编辑 - 这是最好的代码答案:

# -*- coding: utf-8 -*-
import sys
import re
price = sys.argv[1]
new = re.findall(r'[$€£]{1}\d+\.?\d{0,2}',price,re.UNICODE)
for prices in new:
    print prices

3 个答案:

答案 0 :(得分:4)

这是一个与您的示例匹配的正则表达式。

[$€£]\d+(\.\d{2})?

值得注意的是,我假设一段时间后面会有两个数字。所以这将匹配3.50但忽略3.5。如果不需要这种行为,您需要将正则表达式调整为

[$€£]\d+(\.\d{1,2})?

在我的例子中将获得3.5。

答案 1 :(得分:2)

您需要在正则表达式中为您的unicode字符代码添加\u。即

new = re.findall(ur'[\$\u20AC\u00A3]{1}\d+\.?\d{0,2}',string,re.UNICODE)

https://docs.python.org/2/tutorial/introduction.html#unicode-strings

答案 2 :(得分:1)

我可以直接与符号匹配

[\ $ |€|£\ 20AC \ 00A3] {1} \ d +。?\ d {0,2}

http://pythex.org