Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-使用正则表达式查找末尾没有%的数字_Python_Regex - Fatal编程技术网

Python-使用正则表达式查找末尾没有%的数字

Python-使用正则表达式查找末尾没有%的数字,python,regex,Python,Regex,我有以下Python列表: my_list=['Prix TTC欧元:10,10','Prix HT欧元8,42','TVA(20.00%)欧元:1,68'] 我想得到所有的数字,比如10,10,8,42和1,68,没有百分比(20.00%) 我的代码: my_list = ['Prix TTC euros : 10,10', 'Prix HT euros 8,42', 'TVA (20.00%) euros : 1,68'] for item in my_list: try: fou

我有以下Python列表:
my_list=['Prix TTC欧元:10,10','Prix HT欧元8,42','TVA(20.00%)欧元:1,68']

我想得到所有的数字,比如
10,10,8,42
1,68
,没有百分比(20.00%)
我的代码:

my_list = ['Prix TTC euros : 10,10', 'Prix HT euros 8,42', 'TVA (20.00%) euros : 1,68']

for item in my_list:
try:
    found = re.search('([+-]?([0-9]*[,.])?[0-9]+)', item).group()
except AttributeError:
    found = None  # apply your error handling
print(found)
它打印:

10,10
8,42
20.00

我试图逃离最后一个被发现的号码20.00,得到1,68。有没有办法避开以%或其他解决方案结尾的数字。

与其消极地向前看,不如尝试使用一个积极的方法,用
(?=[^0-9,.%]|$)
-“后面跟一些不是
%
的东西,一个数字的其他部分,或者什么都没有”


或者,只需提取
[0-9.,%]+
的所有序列,并使用Python丢弃不正确的匹配项。

有一种方法可以避免将百分比值与单词边界匹配,后跟一个否定的前瞻,这将拒绝后跟
%
符号的匹配项:

import re

my_list = ['Prix TTC euros : 10,10', 'Prix HT euros 8,42', 'TVA (20.00%) euros : 1,68']

for item in my_list:
    found = re.search(r'[-+]?\b(?!\d+(?:[,.]\d+)?%)\d+(?:[.,]\d+)?', item)
    if found:
        print(found.group())
请参阅,输出:
['10,10','8,42','1,68']

另见a:

  • [-+]?
    -可选的
    -
    +
  • \b
    -单词边界
  • (?!\d+(?:[,.]\d+)
    -如果有1+个数字,可选的
    序列,然后是当前位置右侧的1+个数字,则会导致匹配失败
  • \d+
    -1+位
  • (?:[,]\d+)
    -可选的
    序列,然后是1+位

让我们从正则表达式开始:

found = re.search(r'([+-]?(?:[0-9]*[,.])?[0-9]+)', item).group()
这就像你提到的那样。我们需要在这个正则表达式的末尾添加
%
,作为一个负前瞻

found = re.search(r'([+-]?(?:[0-9]*[,.])?[0-9]+)(?!%)', item).group()
上面印着:

10,10
8,42
20.0  # <---- note the last digit is missing here
这就是我们想要的:

10,10
8,42
1,68

哦我的错,数字在美元中也可以有句点。这很好,但只有在“,”前面找到一个空格时才会失败,比如
Prix HT ei:8,42
@siddiquinor
Prix HT ei:8,42
的预期结果是什么?如果您想匹配
8,42
,请使用.Stribizew yes,因为有时我在字符串中发现空格,所以您的建议按预期效果运行。它无法获得预期结果。@siddiquinor我不这么认为,除非我们彼此误解。在regex101网站上查看:是的,你是对的。这也行得通。第二个价格我只得到了8英镑。后来我发现我的第二个价格
8,42
中有一个空格。
10,10
8,42
1,68