Is there a simpler way to write the following regular expression, specifically avoiding all the groupings with the ‘?’ optional character?
/^w(o(r(d)?)?)?$/
It should match the following:
- w
- wo
- wor
- word
and should not match, as mere examples:
- wr
- wd
- woo
- wrr
- wodr
- wrdo
- ord
- rd
- odr
In this particular case its a very short word but you can see by this next example how things can become ugly very fast.
Regex to match vertical or horizontal and any amount of first sequential characters of each word:
/^h(o(r(i(z(o(n(t(a(l)?)?)?)?)?)?)?)?)?|v(e(r(t(i(c(a(l)?)?)?)?)?)?)?)$/
I’m using ruby but I think this question applies to any language that makes use of regular expressions, so I’ll thank answers in any language. Don’t know much about perl, though…
I only found one question similar to mine but doesn’t show any better solution, anyway, here is the link.
You could simplify it with an
ORexpression:or reverse the test by making a regex from the input text (in pseudo code):