gpt4 book ai didi

python - 正则表达式 : may or may not contain a string

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:56 25 4
gpt4 key购买 nike

我想匹配一个可能是 0.1234567 或 1.23e-5 形式的 float 这是我的 Python 代码:

import re
def main():
m2 = re.findall(r'\d{1,4}:[-+]?\d+\.\d+(e-\d+)?', '1:0.00003 3:0.123456 8:-0.12345')
for svs_elem in m2:
print svs_elem

main()

它打印空白...根据我的测试,问题出在 (e-\d+)?部分。

最佳答案

见重点:

Help on function findall in module re:findall(pattern, string, flags=0)    Return a list of all non-overlapping matches in the string.    If one or more groups are present in the pattern, return a    list of groups; this will be a list of tuples if the pattern    has more than one group.    Empty matches are included in the result.

You have a group, so it’s returned instead of the entire match, but it doesn’t match in any of your cases. Make it non-capturing with (?:e-\d+):

m2 = re.findall(r'\d{1,4}:[-+]?\d+\.\d+(?:e-\d+)?', '1:0.00003 3:0.123456 8:-0.12345')

关于python - 正则表达式 : may or may not contain a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com