简体   繁体   English

正则表达式科学计数法

[英]Regex scientific notation

I need to float the following strings that represent scientific notation values without the exponent: 我需要浮动以下表示科学计数法值的字符串而无需指数:

'-1.366-6'
'1.366-6'
'-1.366+6'
'1.366+6'
'-1.25-10'

I need to insert an 'e' before the final + or - 我需要在最后的+或-之前插入“ e”

'-1.366e-6'
'1.366e-6'
'-1.366e+6'
'1.366e+6'
'-1.25e-10'

How can I use regex to achieve this? 我如何使用正则表达式来实现这一目标?

You need to use re.sub , 您需要使用re.sub

re.sub(r'(?=[-+][^-+]*$)', 'e', string)

The above regex matches the boundary which was followed by last + or - character. 上面的正则表达式匹配边界,后跟最后一个+-字符。

DEMO DEMO

Example: 例:

>>> import re
>>> l = ['-1.366-6', '1.366-6', '-1.366+6', '1.366+6', '-1.25-10']
>>> for i in l:
        print(re.sub(r'(?=[-+][^-+]*$)', 'e', i))


-1.366e-6
1.366e-6
-1.366e+6
1.366e+6
-1.25e-10

Note that 注意

re.sub(r'(?=[-+][^-+]*$)', 'e', '+1.3666')

returns 'e+1.3666' . 返回'e+1.3666' If you'd like it to return '+1.3666' , then you could use 如果您希望它返回'+1.3666' ,则可以使用

re.sub(r'(?<=\d)(?=[+-])', 'e', text)

instead. 代替。


import re

tests = [
('-1.366-6', '-1.366e-6'),
('1.366-6',  '1.366e-6' ),
('-1.366+6', '-1.366e+6'),
('1.366+6',  '1.366e+6' ),
('-1.25-10', '-1.25e-10'),
('+1.366', '+1.366'),
]

for text, expected in tests:
    result = re.sub(r'(?<=\d)(?=[+-])', 'e', text)
    print(result)
    assert result == expected

yields 产量

-1.366e-6
1.366e-6
-1.366e+6
1.366e+6
-1.25e-10
+1.366

The pattern (?<=\\d)(?=[+-]) means 模式(?<=\\d)(?=[+-])表示

(?<=      # match if preceded by 
\d        # a digit
 )    
(?=       # match if followed by
[+-]      # a literal plus or minus sign
 )      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM