【问题标题】:Python Regex Search Returns Positive Non-Integer Number <1 As Empty StringPython 正则表达式搜索返回正非整数 <1 作为空字符串
【发布时间】:2021-03-16 01:55:21
【问题描述】:

我正在使用 Python Regex 模块搜索字符串,感兴趣的字符串示例是“*MBps 2.57”。

我正在使用以下代码:

 temp_string = re.search('MBps, \d*\.?\d*', line)
 if (temp_string != None):
     temp_number = re.split(' ', temp_string.group(), 1)

我想查找 MBps > 0 的实例,然后获取该数字并进行处理。

只要MBps后面的数字> 1,代码就可以正常工作。例如,如果它是'MBps 182.57',则RegEx对象转换为字符串时会显示'MBps,182.57'。

但是,当 MBps 后面的数字小于 1 时,例如,如果它是“MBps 0.31”,则返回的 RegEx 对象显示“MBps”但没有数字。它只是第一个匹配之后的一个空字符串。

我尝试了不同的正则表达式匹配策略(re.match、re.findall),但似乎没有一个能正常工作。在 regex101 测试站点中,它显示 regex 表达式有效,但我无法让 Python regex 模块匹配行为。

关于它为什么发生以及如何纠正它的任何想法?

谢谢

【问题讨论】:

  • MBps 0.31MBps 之后不包含逗号。错字?
  • 是的,这是一个错字。它应该是 MBps,0.31

标签: python regex


【解决方案1】:

我会在这里使用re.findall

inp = "The first speed is 3.14 MBps and the second is 5.43 MBps"
matches = re.findall(r'\b(\d+(?:\.\d+)?) MBps\b', inp)
print(matches)

打印出来:

['3.14', '5.43']

【讨论】:

  • 谢谢。我试过了,但仍然无法达到 0.31 MBps。
【解决方案2】:

好的,我找到了一种方法来完成这项工作。

我把代码改成:

temp_string = re.search('MBps, [0-9\.]+', line)
if (temp_string != None):
    temp_number = re.split(' ', temp_string.group(), 1)

这样可以捕获所有数字。我认为在正则表达式匹配中明确而不仅仅是 \d+ 或 \d* 会使这项工作更好。

谢谢

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多