const regex = /(?#skip match process when S exist, or remove optional left most target T, capture left and right part of T.
Use case: if N is not exist, modify/change T to N, or create N. If any create or modify write operated, appending output N to right.
skip exist:)^(?!.*S)(?#
captrue prefix :)^(.*?)(?#
optional target to remove:)(?:T|$)(?#
captrue postfix:)(.*?)$(?#
Test string:
aa
aaT
Tcc
aaTcc
aaTbbTcc
aaS
aaTS
TccS
aaTccS
Saa
SaaT
STcc
SaaTcc
Substitution: $1$2N
Return:
aaN
aaN
ccN
aaccN
aabbTccN
aaS
aaTS
TccS
aaTccS
Saa
SaaT
STcc
SaaTcc)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?#skip match process when S exist, or remove optional left most target T, capture left and right part of T.
Use case: if N is not exist, modify\/change T to N, or create N. If any create or modify write operated, appending output N to right.
skip exist:)^(?!.*S)(?#
captrue prefix :)^(.*?)(?#
optional target to remove:)(?:T|$)(?#
captrue postfix:)(.*?)$(?#
Test string:
aa
aaT
Tcc
aaTcc
aaTbbTcc
aaS
aaTS
TccS
aaTccS
Saa
SaaT
STcc
SaaTcc
Substitution: $1$2N
Return:
aaN
aaN
ccN
aaccN
aabbTccN
aaS
aaTS
TccS
aaTccS
Saa
SaaT
STcc
SaaTcc)', 'gm')
const str = `aa
aaT
Tcc
aaTcc
aaTbbTcc
aaS
aaTS
TccS
aaTccS
Saa
SaaT
STcc
SaaTcc`;
const subst = `$1$2N`;
// 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