python - 用于匹配非整数的 float 的正则表达式

标签 python regex

<分区>

我有以下用于在字符串中查找数字的正则表达式

-?\d*\.?\d+([eE][-+]?\d+)?

并希望对其进行修改,使其匹配 float 而非整数。这样做的标准(据我所知)是匹配必须至少具有以下之一:.eE。但是,我想不出一个很好的方法来将此要求合并到正则表达式中而不复制主体的大部分内容。

重复

经过一番搜索,我找到了 Regular expressions match floating point number but not integer尽管标题不明确,但与此问题完全相同(包括 soln)。

最佳答案

以下正则表达式执行此操作,尽管它有点含糊:

-?(?:\d+())?(?:\.\d*())?(?:e-?\d+())?(?:\2|\1\3)

解释:

一个数由三部分组成(整数部分、小数部分和指数部分)。如果存在小数部分,则它是一个 float,但如果它不存在,则当指数部分后跟时,该数字仍然可以是一个 float 。

这意味着我们首先必须在正则表达式中将所有三个部分设为可选。但随后我们需要构建规则来准确指定需要哪些部分才能形成有效的 float 。

幸运的是,有一个技巧可以让我们做到这一点。空捕获组 (()) 始终匹配(空字符串)。对该组 (\1) 的反向引用只有在该组参与了比赛时才会成功。通过在每个可选组中插入一个(),我们稍后可以测试所需的部分是否参与了匹配。

例如,在 Python 中:

regex = re.compile(r"""
    -?    # Optional minus sign
   (?:    # Start of the first non-capturing group:
    \d+   #  Match a number (integer part)
    ()    #  Match the empty string, capture in group 1
   )?     # Make the first non-capturing group optional
   (?:    # Start of the second non-capturing group:
    \.\d* #  Match a dot and an optional fractional part
    ()    #  Match the empty string, capture in group 2
   )?     # Make the second non-capturing group optional
   (?:    # Start of the third non-capturing group:
    e     #  Match an e or E
    -?    #  Match an optional minus sign
    \d+   #  Match a mandatory exponent
    ()    #  Match the empty string, capture in group 3
   )?     # Make the third non-capturing group optional
  (?:     # Now make sure that at least the following groups participated:
   \2     #  Either group 2 (containing the empty string)
  |       # or
   \1\3   #  Groups 1 and 3 (because "1" or "e1" alone aren't valid matches)
  )""", re.I|re.X)

测试套件:

>>> [match.group(0) for match in
...        regex.finditer("1 1.1 .1 1. 1e1 1.04E-1 -.1 -1. e1 .1e1")]
['1.1', '.1', '1.', '1e1', '1.04E-1', '-.1', '-1.', '.1e1']

关于python - 用于匹配非整数的 float 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547981/

相关文章:

javascript - 从 javascript 中的对象数组替换模板中的键

c# - Python 到 C# 的转换

python - 如何使用python使用firestore字段增量?

python : Revert to base __str__ behavior

python - 在 Python 2.7 中使用 re.sub 时出现错误 "unmatched group"

javascript - 将字符串切割成 'variable' 长 block

Java - 使用 "\\"作为分隔符时出现正则表达式错误

python - 尝试安装 python 时出现错误

python - 获取 auth_user 的所有 Django 级联依赖模型

javascript - 为什么这个 p 标签被添加为新行?