匹配数字字符串对 [英] Matching number string pairs

查看:39
本文介绍了匹配数字字符串对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例字符串:

 R10666: 273141 C1 + 273141 C2 + 273141 C3 + 273141 C4 + 273141 C5 - 273141 C6

我想获得:

[('273141','C1'), ..., ('- 273141', 'C6')]

数字可以是具有指数符号的浮点数,即- 2.5e-7.

The numbers can be floating point numbers with exponential notation i.e. - 2.5e-7.

我当前的正则表达式如下所示:

My current regex looks like this:

re.findall(r'([+-]? \d+(\.\d*)?|\.\d+([eE][+-]?\d+)?)( [a-zA-Z0-9_]+)', split)

但是它没有产生正确的输出,它有什么问题?

But it doesn't produce the correct output, what is wrong with it?

这是一个示例输出:

(' 273141', '', '', ' C1')

或者什么都不匹配.

推荐答案

我改编了浮点数使用正则表达式 regex 并稍微缩短正则表达式(注意替代列表消失了,这意味着更少的回溯,并且前面的 (?i) 不区分大小写的匹配选项可以转[A-Za-z] 变成 [az]):

I adapted the Floating Point Numbers with a Regular Expression regex for you and shortened the regex a bit (note the alternative list is gone that means less backtracking, and the (?i) case insensitive matching option in front to turn [A-Za-z] into [a-z]):

import re
s = "R10666: 273141 C1 + 273141 C2 + 273141 C3 + 273141 C4 + 273141 C5 - 273141 C6"
print re.findall(r'(?i)([-+]?\s*\d*\.?\d+(?:[eE][-+]?\d+)?)(\s+\w+)', s)

IDEONE 演示的输出:

[(' 273141', ' C1'), ('+ 273141', ' C2'), ('+ 273141', ' C3'), ('+ 273141', ' C4'), ('+ 273141', ' C5'), ('- 273141', ' C6')]

这篇关于匹配数字字符串对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆