in reply to simple regexp problem

Square brackets don't mean what you think they mean. Use (?:...) to group things without capturing, and use the ? suffix to make something optional.

/^(\w+)(?:_(\w+))?$/

Replies are listed 'Best First'.
Re^2: simple regexp problem
by ikegami (Patriarch) on Dec 05, 2005 at 17:46 UTC
    Ah shoot! While the advice in the above post is sound, the code won't work because "\w" includes "_"! Fix:
    /^([a-zA-Z0-9+])(?:_(\w+))?$/

    or

    /^((?:(?!_)\w)+)(?:_(\w+))?$/
      This works too: /^(\w+?)(?:_(\w+))?$/ But why the last ? ? If I leave it off, it doesn't parse the string "AAAAAAA"

      Thanks
      Luca

        atom? (as opposed to atom??, atom*? and atom+?) means atom is optional. In other words, it provides the "optionally" in "you want AAAAAA optionally followed by _BBBBBB".