Skip navigation
scriptworker
Currently Being Moderated

variables in regexp

Apr 19, 2012 7:43 AM

Hello,

 

Is there a way to use variables in regular expressions?

Can't find the right syntax.

 

var pattern = RegExp('/\n\d\t[^\t]+\t\d\t/' + var);

 

This does not work.

 

Michel

 
Replies
  • Currently Being Moderated
    Apr 19, 2012 8:41 AM   in reply to scriptworker

    Hi Michel,

     

    By 'variable' you mean any expression which can be coerced into a String, right? The point is to clearly make a distinction between a regex pattern (which is a string) and the RegExp instance itself:

     

    var myString = "Hello";
    var myPattern = "\\n\\d\\t[^\\t]+\\t\\d\\t" + myString;
    var myRegex = new RegExp(myPattern, 'g');
     
    // myRegex is then equivalent to: /\n\d\t[^\t]+\t\d\tHello/g
    

     

    Note that all regular expression metacharacters such as \n or \d must be double-escaped when you introduce them through a literal string (cf. myPattern declaration).

     

    @+

    Marc

     
    |
    Mark as:
  • John Hawkinson
    5,512 posts
    Jun 25, 2009
    Currently Being Moderated
    Apr 19, 2012 11:08 AM   in reply to Marc Autret

    I would write Marc's example using this horrible construct:

     

    var myString = "Hello";
    var myPattern = /\n\d\t[^\t]+\t\d\t/.source + myString;
    var myRegex = new RegExp(myPattern, 'g');

     

    because it avoids the double-quoting.

     
    |
    Mark as:
  • Currently Being Moderated
    Apr 19, 2012 1:41 PM   in reply to John Hawkinson

    John Hawkinson wrote:

     

    ...using this horrible construct:

     

     

    Nice! I don't think I've seen that one before.

     

    Harbs

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points