in reply to combining RegEx

For some reason, it's hard to visualize the precedence in a regex; maybe it's the lack of whitespace (unless you use //x). Anyway, your attempt has a precedence problem. It's parsed as a match of either /SW=?/ or /:?\s*(..../. Enclose the | and its choices in (?:   ) like so: /SW(?:=?|:?)\s*.../ though you don't need ? on both alternatives. In fact, you could say (?:=|:|) (using an empty alternative) or (?:=?|:) or (?:=|:)? or [=:]?.

By "ignore the word 'SWITCH'" do you mean allow SWITCH or SW interchangably? If so, replace SW with SW(?:ITCH)?.

Replies are listed 'Best First'.
Re: Re: combining RegEx
by Anonymous Monk on Nov 04, 2003 at 15:40 UTC
    Can I use a string in brackets like so to match either 'Rel' or 'Release'?
    '\s+Rel[ease]?\.?\s*([^\s;,\n\r]+)',
      No, you can't. Character classes are for characters, not strings. Use (?:ease)?.

      And that other character class you have is a bit redundant; \s contains \n and \r.

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

      No, [ease] is the same as [aes] and means one character which may be one of 'a', 'e', or 's'. What you want is the string ease modified by the "match either one or zero times" qualifier '?'. Since '?' has high precedence, saying ease? means the string "eas" optionally followed by 'e'. To make the '?' apply to the whole string "ease", you enclose it in parentheses (ease)?.

      Since parentheses have two functions (to affect precedence and to cause capture of a submatch (e.g. into $1)) and you often want to do the former but not the latter, there is a special form of parentheses that don't capture: (?: before and ) after. This odd way of extending regex syntax was chosen since (? regex was otherwise meaningless and illegal.

      Does that help?

      You can install modules YAPE::Regex and YAPE::Regex::Explain and say (for example) print YAPE::Regex::Explain->new("(ease)?")->explain() to get a verbose blow-by-blow description of what a particular regex does.

        Very much...Thanks :)