3 Replies Latest reply on Apr 19, 2012 1:41 PM by Harbs.

    variables in regexp

    scriptworker

      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

        • 1. Re: variables in regexp
          Marc Autret Level 4

          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

          • 2. Re: variables in regexp
            John Hawkinson Level 5

            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.

            • 3. Re: variables in regexp
              Harbs. Level 6

              John Hawkinson wrote:

               

              ...using this horrible construct:

               

               

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

               

              Harbs