Skip to main content
 首页 » 编程设计

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

2024年11月24日31webabcd

我有以下正则表达式 \.(?![^.]+$)|[^-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. 

正则表达式电路

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

演示

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

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);