import re
regex = re.compile(r"^(?:[^_]*_){3}([^_]+_[^_]+)_(?:[^_]+_){3}([^_]+_[^_]+).*", flags=re.MULTILINE)
test_str = ("a_b_c_d_e_f_g_1_2_3_4_5\n"
"_b_c_dd_ee_f_g_1_222_333_4_5\n"
"b_c_dd_ee_f_g_1_222_333_4_5\n"
"_c_dd_ee_ff_g_1_222_333_444_5\n"
"c_dd_ee_ff_g_1_222_333_444_55_66\n"
"_dd_ee_ff_gg_1_222_333_444_55_66")
subst = "$1_$2"
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html