python - 正则表达式仅包含第一次遇到 "-"和 "."

标签 python regex floating-point data-cleaning

我有以下正则表达式 \.(?![^.]+$)|[^-0-9.] 清除数字中的所有字符并只保留第一个 ' .' (因此最后匹配)因为它可以是一个 float 。但是,一些数字也可以是负数和/或内部有“-”,如下所示:

-1.06581.4e-14

如何使我已有的正则表达式也只匹配最后一次遇到的负号? 我的最终数字必须如下所示:

-1.06581414

最佳答案

如果我们希望用科学数字替换 .e,这个表达式可能会这样做,我已经添加了几个可选的边界,因为我不太确定其他输入:

([-+]?\d+)(\.\d+)?((\.)(\d+)(e)([-+])(\d+))?

它有 8 个捕获组,所有隔间都是一个科学数字,如果需要,我们可以对其进行简化。

Demo

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([-+]?\d+)(\.\d+)?((\.)(\d+)(e)([-+])(\d+))?"

test_str = ("-1.06581.4e-14\n"
    "1.06581.4e-14\n"
    "1.06581.4e+14\n"
    "+1.06581.4e-14\n"
    "+1.06581\n"
    "1.06\n"
    "1")

subst = "\\1\\2\\5\\8"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

enter image description here

正则表达式电路

jex.im可视化正则表达式:

enter image description here

演示

这个片段只是展示了捕获组是如何工作的:

const regex = /([-+]?\d+)(\.\d+)?((\.)(\d+)(e)([-+])(\d+))?/gm;
const str = `-1.06581.4e-14
1.06581.4e-14
1.06581.4e+14
+1.06581.4e-14
+1.06581
1.06
1`;
const subst = `$1$2$5$8`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

关于python - 正则表达式仅包含第一次遇到 "-"和 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428406/

相关文章:

python regex 简单帮助 - 处理括号

python - 使用正则表达式验证用户输入

c# - .Net 简单正则表达式二次复杂度

python - 如何在 Python 中递归遍历目录,同时忽略某些子目录?

python - 使用模拟测试构造函数

android - 如何在 Android 中以有意义的形式显示 Float/Double

c++ - 应用于浮点值时,std::abs 和 std::fabs 之间有什么区别吗?

c# - 将float数组写入二进制文件c#

python - python numpy poission 可以生成一个 float 吗?

python - Scipy 的相关函数很慢