Reputation: 14140
I have the regex:
var reValid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*)*$/;
Which validates a CSV file, but I want to be able to modify the delimiter (') with any delimiter.
Is it possible to run a regex replace on a regex?
Example - use a backtick (`) as the delimiter:
var reValid = /^\s*(?:`[^`\\]*(?:\\[\S\s][^`\\]*)*`|[^,`\s\\]*(?:\s+[^,`\s\\]+)*)\s*(?:,\s*(?:`[^`\\]*(?:\\[\S\s][^`\\]*)*`|[^,`\s\\]*(?:\s+[^,`\s\\]+)*)\s*)*$/;
Upvotes: 1
Views: 249
Reputation: 141917
Sure, just use the source property to get the expression as a string, do your replacement, and then create a new RegExp object with the new expression:
var reValid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,'\s\\]*(?:\s+[^,'\s\\]+)*)\s*)*$/;
reValid = RegExp(reValid.source.replace(/'/g, '`'));
Upvotes: 4