const regex = /(?xXmi)
(?:
(?# use non-capture for details in debugging)
(?:
(?<match>
(?# If quoted value)
(?<quot_char>(?<!\\)["'])
(?# Quoted content)
(?:
(?:
(?# Match as many characters that aren't quotation char)
(?# or escape char as possible. )
(?:(?:(?!\k<quot_char>|\\)).+)
(?:
(?# Match any/all escape chars that do not have the)
(?# quotation char following it. )
(?:(?:\\)*(?!\k<quot_char>))?
(?# If there is an escape char followed by the quotation)
(?# quotation char match them. )
(?:[\\]\k<quot_char>)?
)*?
)
)
(?<close_quot>\k<quot_char>)
|
(?# if simple token)
(?<basic>[^ \n]+)+
)
)
(?<trail_ws>[ ]+)?
)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?xXmi)
(?:
(?# use non-capture for details in debugging)
(?:
(?<match>
(?# If quoted value)
(?<quot_char>(?<!\\\\)["\'])
(?# Quoted content)
(?:
(?:
(?# Match as many characters that aren\'t quotation char)
(?# or escape char as possible. )
(?:(?:(?!\\k<quot_char>|\\\\)).+)
(?:
(?# Match any\/all escape chars that do not have the)
(?# quotation char following it. )
(?:(?:\\\\)*(?!\\k<quot_char>))?
(?# If there is an escape char followed by the quotation)
(?# quotation char match them. )
(?:[\\\\]\\k<quot_char>)?
)*?
)
)
(?<close_quot>\\k<quot_char>)
|
(?# if simple token)
(?<basic>[^ \\n]+)+
)
)
(?<trail_ws>[ ]+)?
)', 'gm')
const str = `-t1a1
-t2a1 -t2a2
-t3a1 -t3a2
-t4a1 Test1value -t4a2 test4a2value -t4a3 t4a3value
-t5a1EscQuot \\'t5a1valueESQ\\' -t5a2EscQuot \\"t5a2valueEDQ\\"
-t6a1 "t6a1value1DQWord1 t6a1value1DQWord1" -t6a2SQuot 't6a2value1SQWord1 t6a2value1SQWord2 t6a2value1SQWord3 '
-t7a1SQuotEmpty '' -t7a2DQuotEmpty ""
`;
const subst = `\n${match}`;
// 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