const regex = /(\d)(?=\d*:)(?=.{6}(\d)\d*~.*?(\1;.*?\2_(\d)|\2;.*?\1_(\d)))|(\d)(?=\d*~)(?<=(\d)..{6})(?=\d*~.*?(\6;.*?\7_.*?(!|;)|\7;.*?\6_.*?(!|;)))(?=\d*~.*~.*?(\9(.)|\10(.)))|~.*?~.*?~/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\d)(?=\\d*:)(?=.{6}(\\d)\\d*~.*?(\\1;.*?\\2_(\\d)|\\2;.*?\\1_(\\d)))|(\\d)(?=\\d*~)(?<=(\\d)..{6})(?=\\d*~.*?(\\6;.*?\\7_.*?(!|;)|\\7;.*?\\6_.*?(!|;)))(?=\\d*~.*~.*?(\\9(.)|\\10(.)))|~.*?~.*?~', 'g')
const str = `382829:239091~0;0_01_12_23_34_45_56_67_78_89_9!1;1_22_33_44_55_66_77_88_9!9_02;2_43_54_65_76_87_9!8_09_13;3_64_75_86_9!7_08_19_24;4_85_9!6_07_18_29_35;5_06_17_28_39_46;6_27_38_49_57;7_48_59_68;8_69_79;9_8~!0;1~~01234567890`;
const subst = `$4$5$12$13`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', 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 JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions