Forum: Ruby Regex question - any alternative to: "(_|-| )?"

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2016-10-25 14:04
Hey.

I have a regex question.

Consider user input like:

    foo bar
    foo_bar
    foo-bar

I need to make sure that these possibilities exist but only
these three.

The following regex works:

    (_|-| )?

As in:

    foo(_|-| )?bar

But I was wondering,is there any alternative that is nicer to read?

I am especially wondering because at some later time, perhaps I
may need to enable more character tokens, such as ',' so my
example may become fairly long eventually in the long run.
B078cb4f4fb473c7a54d1fc36d10c70e?d=identicon&s=25 Regis d'Aubarede (raubarede)
on 2016-10-25 20:21
This one should work :
   /foo[\s_\-]bar/
150e3d60e1da33d0ef45a3fab66d6019?d=identicon&s=25 B. Onzo (bonzo_goat)
on 2016-10-26 18:06
Robert Heiler wrote in post #1185181:
> Hey.
>
> I have a regex question.
>
> Consider user input like:
>
>     foo bar
>     foo_bar
>     foo-bar
>
> I need to make sure that these possibilities exist but only
> these three.
>
> The following regex works:
>
>     (_|-| )?
[...]

Have you yet noticed that that regex doesn't match only those 3 inputs
due to the ?-quantifier?
This topic is locked and can not be replied to.