jazzpi
jazzpi

Reputation: 1429

Matching multiple optional characters depending on each other

I want to match all valid prefixes of substitute followed by other characters, so that

My current Regex is /^s(u(b(s(t(i(t(u(te?)?)?)?)?)?)?)?)?/, which works, however this seems a bit verbose.

Is there any better (as in, less verbose) way to do this?

Upvotes: 2

Views: 83

Answers (2)

alpha bravo
alpha bravo

Reputation: 7948

you could use a two-step regex

  1. find first word of subject by using this simple pattern ^(\w+)
  2. use the extracted word from step 1 as your regex pattern e.g. ^subs against the word substitute

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

This would do like the same as you mentioned in your question.

^s(?:ubstitute|ubstitut|ubstitu|ubstit|ubsti|ubst|ubs|ub|u)?

The above regex will always try to match the large possible word. So at first it checks for substitute, if it finds any then it will do matching else it jumps to next pattern ie, substitut , likewise it goes on upto u.

DEMO 1 DEMO 2

Upvotes: 2

Related Questions