我有一个这样的字符串 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/