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

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.

This one should work :
/foo[\s_-]bar/

Robert H. 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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs