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

Imagine I have a string that begins abc in the first three characters, but then ends with either def or xyz. If I wanted to write a regex to match these I would write the following... however, can someone show me how to use OR (|) such that it can go abc(def|xyz) as I can't seem to make it work :(

m/abcdef|abcxyz/

Surely I don't need to duplicate the abc bit twice as although it seems trivial here, in more complex apps it could lead to much bigger regexes?

Replies are listed 'Best First'.
Re: Using OR () in Regex
by larsen (Parson) on May 05, 2002 at 14:07 UTC
    if ( $string =~ m/abc(?:def|xyz)/ ) { print "ok!" }
    You could do the same with:
    if ( $string =~ m/abc(def|xyz)/ ) { # I didn't use ?: print "ok!" }
    but in this case the regexp would spit out in $1 'def' or 'xyz', which probably you don't want. Look at the Regexp Documentation for further details.
Re: Using OR () in Regex
by japhy (Canon) on May 05, 2002 at 14:17 UTC
    You wrote it already: /abc(def|xyz)/ works.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Thats interesting - I was under the impression brackets were used as a memory more than a precedence operator... do they provide precedence in the conventional sense of the word and therefore why does this not work...

      m/(\S=\S)|( =\S)|(\S= )/g

      ... to look for all the occurences of an equals sign that is not got whitespace on either side?

      Thanks.

        I have yet to see your code where that regex "does not work". It works for me.

        _____________________________________________________
        Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;