1

I want to modify an invalid regex rather than throw an error, but I can't get the string of the invalid regex before the error is thrown...

var rex = /t(h)?u(?(1)r|e)sday/.replace(/\(\?\((\d)\)(.+?\|)(.+?)\)/g,'((?!\\$1)$2\\$1$3)').replace(/^\/|\/$/g,'')

This works, but is clearly not the solution I am looking for...

try{
  var rex = /t(h)?u(?(1)r|e)sday/
} catch(e){
  var rex = new RegExp(e.toString().split(/: /)[2].replace(/\(\?\((\d)\)(.+?\|)(.+?)\)/g,'((?!\\$1)$2\\$1$3)').replace(/^\/|\/$/g,''))
}
console.log(rex)

I want to be able to define the regex as a regex, not as a string. Can it be done?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • What are you trying to do with this? – Blender Feb 22 '13 at 11:12
  • I want to be able to define what javascript considers to be invalid regex (in this case, including a conditional `(?(1)r|e)`), and intercept and modify (so it can be sanitised) it, before the interpreter throws an error. – Billy Moon Feb 22 '13 at 11:15
  • DUPLICATE QUESTION, you also asked http://stackoverflow.com/questions/15022635/i-would-like-to-mimick-conditionals-in-javascript-regex – Mörre Feb 22 '13 at 11:28
  • Please explain "I want to be able to define the regex as a regex, not as a string". – MikeM Feb 22 '13 at 11:52
  • @Mörre it is not a duplicate question, they are two independent questions relating to the same ultimate task. One is about the format of defining regex, and one is about the modification of that regex... thanks for noticing them both :) – Billy Moon Feb 22 '13 at 11:55
  • @MikeM I want to be able to define a regex, with conditionals, in the usual manner, as a regex, and then modified, rather than defining it as a string, and then modifying it and turning it into a regex afterwards. The issue I am having is, as soon as I define it as a regex, it throws an error, before I have the chance to intercept, and modify it. Therefore, the only option left, is to define it as a string, then modify the string into valid javascript regex, then convert it into a regex. – Billy Moon Feb 22 '13 at 11:57

1 Answers1

1
var rex, str = 't(h)?u(?(1)r|e)sday';
try{
  rex = new RegExp( str );
} catch (e) {
  rex = new RegExp( str.replace( /\(\?\((\d)\)(.+?\|)(.+?)\)/g, '((?!\\$1)$2\\$1$3)'; ).replace( /^\/|\/$/g,'' ) )
}
console.log( rex )
MikeM
  • 13,156
  • 2
  • 34
  • 47
  • Well, that is better than the way I did it - thanks, but still does not achieve what I want. I really want to be able to make the original definition as a regex, and then modify it later. I am aiming eventually, to extend the RegExp prototype to be able to modify cases like this, so as a first step, I am trying to ascertain, if it is possible to catch and modify invalid regex. – Billy Moon Feb 22 '13 at 12:17