python - 正则表达式从字符串python中提取三个字符

标签 python regex

我有一个这样的字符串 testing_7_3_4_testing

我想用 testing_7.3.4_testing 替换 testing_7_3_4_testing,我试过使用 str.replace(/\d_\d/, ".") 我得到了一些非常奇怪的结果。正则表达式专家请帮忙!

最佳答案

试试这个:

import re

my_strs = [
    'testing_7_3_4_testing',
    'testing_7_3_testing',
    'testing_7_3_4_5',
    'testing_71_312_4123_testing',
]

pattern = r"""
    (\d+)      #Match a digit, one or more times, captured in group 1, followed by...
    _          #an underscore, followed by...
    (?=\d+)    #a digit, one or more times, but do not include as part of the match
"""

for my_str in my_strs:
    new_str = re.sub(pattern, r'\1.', my_str, flags=re.X)
    print(new_str)

--output:--
testing_7.3.4_testing
testing_7.3_testing
testing_7.3.4.5
testing_71.312.4123_testing

模式 (?=\d+) 说要匹配一个数字一次或多次,但实际上并不包括匹配的数字作为匹配的一部分。

关于python - 正则表达式从字符串python中提取三个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005323/

相关文章:

python - 根据行/列条件创建 DataFrame 掩码

python - "Too many values to unpack"异常

javascript - 正则表达式删除扩展名和号码

.net - 使用 Powershell 正则表达式查找 PHP 字符串,例如 "<?php eval "

Python 无法构建查询字符串

python - 从 txt.file 读取时间戳并使用 matplotlib (Web 服务器)将它们绘制在 X 轴上

python - 如何调整Matplotlib.Axes.scatter方法中的 'c'参数?

javascript - 从 Chrome 到 Internet Explorer 的不同正则表达式

regex - r 正则表达式奇怪的行为

java - 单个模式中的多个匹配项?