简体   繁体   中英

Matching multiple optional characters depending on each other

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

  • sub/abc/def matches the sub part.
  • substitute/abc/def matches the substitute part.
  • subt/abc/def either doesn't match or only matches the sub part, not the t .

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?

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

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 eg ^subs against the word substitute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM