[英]Regex to extract three characters from string python
我有一个字符串,例如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+)
表示要匹配一次或多次,但实际上不包括匹配数字作为匹配的一部分。
将每个数字保存到自己的保存组中 ,在替换字符串中引用这些组:
>>> import re
>>> s = "testing_7_3_4_testing"
>>> re.sub(r"(\d)_(\d)_(\d)", r"\1.\2.\3", s)
'testing_7.3.4_testing'
或者,我们可以使用替换函数 ,与第一种方法相比,该函数还处理输入字符串中可变数目的数字:
>>> def replacement(m):
... x, y, z = m.groups()
... return x + y.replace("_", ".") + z
...
>>> re.sub(r"(.*?_)([0-9_]+)(_.*?)", replacement, s)
'testing_7.3.4_testing'
非正则表达式方法将涉及通过_
,切片和连接进行拆分:
>>> l = s.split("_")
>>> l[0] + "_" + ".".join(l[1:-1]) + "_" + l[-1]
'testing_7.3.4_testing'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.