python - 正则表达式使用递增的数字序列 Python

标签 python regex string sequential

假设我有一个字符串:

teststring =  "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" 

我想要的是:

testlist = ["1.3 Hello how are you", "1.4 I am fine, thanks 1.2 Hi There", "1.5 Great!"]

基本上,仅在差异为 .1(即 1.2 到 1.3)的递增数字上拆分。

有没有办法用正则表达式拆分它,但只捕获递增的序列号?我用 Python 编写了代码,通过对每个代码使用自定义的 re.compile() 进行顺序迭代,这没问题,但非常笨拙。

像这样(其中 parts1_temp 是字符串中 x.x. 数字的给定列表):

parts1_temp = ['1.3','1.4','1.2','1.5']
parts_num =  range(int(parts1_temp.split('.')[1]), int(parts1_temp.split('.')[1])+30)
parts_search = ['.'.join([parts1_temp.split('.')[0], str(parts_num_el)]) for parts_num_el in parts_num]
#parts_search should be ['1.3','1.4','1.5',...,'1.32']

for k in range(len(parts_search)-1):
    rxtemp = re.compile(r"(?:"+str(parts_search[k])+")([\s\S]*?)(?=(?:"+str(parts_search[k+1])+"))", re.MULTILINE)
    parts_fin = [match.group(0) for match in rxtemp.finditer(teststring)]

但是人是丑陋的。有没有办法在正则表达式中更直接地做到这一点?我想这是有人在某个时候想要使用正则表达式的功能,但我找不到任何关于如何解决这个问题的想法(也许纯正则表达式是不可能的)。

最佳答案

使用正则表达式来做这件事似乎过于复杂。这个处理怎么样:

import re

teststring =  "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" 
res = []
expected = None
for s in re.findall(r'\d+(?:\.\d+)?|\D+', teststring):
    if s[0].isdigit() and expected is None:
        expected = s
        fmt = '{0:.' + str(max(0, len(s) - (s+'.').find('.') - 1)) + 'f}'
        inc = float(re.sub(r'\d', '0', s)[0:-1] + '1')
    if s == expected:
        res.append(s)
        expected = fmt.format(float(s) + inc)
    elif expected:
        res[-1] = res[-1] + s

print (res)

如果数字恰好有 2 位小数或更多,或者没有,这也适用。

关于python - 正则表达式使用递增的数字序列 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835481/

相关文章:

python - 使用python将excel文件中的数据导入SQL Server

python - 在 webapp2 中部署时缩小/压缩 javascript 和 css?

python - bool 表达式中的正则表达式

java - 在 Java 中删除反斜杠和换行符(一起出现)

javascript - 正则表达式允许字母和数字但不允许单独的数字

python - 如果我将通常调用的代码放入单独的方法或文件中,Python 会更快吗?

python - Selenium send_keys() 消息 : element not interactable

c++ - 如何将可变数量的char数组元素转换为字符串

java - 如何遍历字符串以确保它仅在某些位置包含数字?

c++ - 为什么 std::string::max_size 不是编译时常量?