Python regex “OR” gives empty string when using findall

余生长醉 提交于 2021-01-28 05:21:31

问题


I'm using a simple regex (.*?)(\d+[.]\d+)|(.*?)(\d+) to match int/float/double value in a string. When doing findall the regex shows empty strings in the output. The empty strings gets removed when I remove the | operator and do an individual match. I had also tried this on regex101 it doesn't show any empty string. How can I remove this empty strings ? Here's my code:

>>>import re
>>>match_float = re.compile('(.*?)(\d+[.]\d+)|(.*?)(\d+)')
>>>match_float.findall("CA$1.90")  
>>>match_float.findall("RM1")

Output:

>>>[('CA$', '1.90', '', '')]
>>>[('', '', 'RM', '1')]

回答1:


Since you defined 4 capturing groups in the pattern, they will always be part of the re.findall output unless you remove them (say, by using filter(None, ...).

However, in the current situation, you may "shrink" your pattern to

r'(.*?)(\d+(?:\.\d+)?)'

See the regex demo

Now, it will only have 2 capturing groups, and thus, findall will only output 2 items per tuple in the resulting list.

Details:

  • (.*?) - Capturing group 1 matching any zero or more chars other than line break chars, as few as possible up to the first occurrence of ...
  • (\d+(?:\.\d+)?) - Capturing group 2:
    • \d+ - one of more digits
    • (?:\.\d+)? - an optional *non-*capturing group that matches 1 or 0 occurrences of a . and 1+ digits.

See the Python demo:

import re
rx = r"(.*?)(\d+(?:[.]\d+)?)"
ss = ["CA$1.90", "RM1"]
for s in ss:
    print(re.findall(rx, s))
# => [('CA$', '1.90')]  [('RM', '1')]


来源:https://stackoverflow.com/questions/45876194/python-regex-or-gives-empty-string-when-using-findall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!