Elk*_*lke 0 python regex python-2.7
我有一个包含多个数字的字符串,需要在某些(不是全部)数字中添加前导零.只有单个数字并且前面有字母的数字需要前导零.
输入: "Z9_M50_P3_2X_MY_STRING"
输出: "Z09_M50_P03_2X_MY_STRING"
试试这个:
(?<=[a-zA-Z])(\d)(?!\d)
Run Code Online (Sandbox Code Playgroud)
替换为:
0\1
Run Code Online (Sandbox Code Playgroud)
样本来源:( 在这里运行)
import re
regex = r"(?<=[a-zA-Z])(\d)(?!\d)"
test_str = ("Z9_M50_P3_2X_MY_STRING")
subst = "0\\1"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
Run Code Online (Sandbox Code Playgroud)