1

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*)*$/;
2
  • It is possible but could lead to unexpected behaviour... Build the regex using a variable for the delimiter and the RegExp object. That ensures only the positions that need the delimiter are affected. Commented Apr 22, 2012 at 7:13
  • @sg3s That's what I did, and it worked... Commented Apr 22, 2012 at 7:55

1 Answer 1

4

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, '`'));
Sign up to request clarification or add additional context in comments.

1 Comment

One issue, if the original regex has modifiers /[regex]/g you need to re-add them. It doesn't apply to the example I posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.