cosmicperl has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
  Just a quickie. If I have a list of compiled regexps, is there a way of turning them back into normal regexps?
  I'm sending some validation regexps over to JavaScript, but JavaScript doesn't understand compiled regexps, only normal ones.

Lyle

Replies are listed 'Best First'.
Re: Can qr be un-compiled?
by Fletch (Bishop) on Feb 03, 2009 at 13:28 UTC

    As is pointed out above, Perl regexen and JavaScript regexen are similar but different sublanguages. For simple stuff you may be able to get away with passing JS the stringified version, but a safer alternative would be to use YAPE::Regex to get a parse tree you could walk and translate/downgrade to something suitable for JS.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      sub re_p2js { local @_ = @_; for( @_ ) { 1 while s[^\(\?(\w*)-?\w*:(.*)\)$][/$2/$1] } @_ } print for re_p2js qr/abcde/, qr/(1|2)z$/, qr/^abcd*/ims
      This will extract the outer (?-xims:) -- and it may be enough for your purposes but, as others already posted, it will not compile perl regexen into js regexen.

      UPDATE: changed to respect the flags. The output will be:

      /abcde/ /(1|2)z$/ /^abcd*/msi
      []s, HTH, Massa (κς,πμ,πλ)
        Fails for qr/\//
        Perfect, thanks :)
Re: Can qr be un-compiled?
by ikegami (Patriarch) on Feb 03, 2009 at 13:11 UTC

    It stringifies to a pattern.

    >perl -le"print qr/abc/" (?-xism:abc)

    Note that JavaScript and Perl's regexp languages differ.

    Update: Added example

      my $cregexp = qr/[a-z].*?[0-9] $/is; print $cregexp; prints: (?si-xm:[a-z].*?[0-9] $)
      JavaScript doesn't understand regexps that look like that:-
      http://docs.sun.com/source/816-6408-10/regexp.htm


      Lyle
      -Update: ikegami's original response didn't have an example, hence mine.
      ikegami - It would be nice if you listed updates you make to your replies

        I don't immediately have the means of converting a Perl regexp pattern into a JavaScript regexp pattern, but I got you half way there by answering your question. "[a-z].*?[0-9] $" would not be equivalent to the compiled regexp.

        If you're dealing with the subset that's compatible to both, why don't you just keep the pattern and the compiled regexp separately?

        my %regexps = map { $_ => qr/$_/ } @regexps;
Re: Can qr be un-compiled? (re+=1)
by tye (Sage) on Feb 03, 2009 at 15:34 UTC
    for( @regexes ) { s/^\(\?[-\w]*://; s/)$//; }

    - tye        

      /i is ok. JavaScript understands that. I was thinking of just re-creating the string with a regexp in the first place, but thought there might be a proper way of doing it... Seems I should have just gone with my gut :/