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
.
you could use a two-step regex
^(\\w+)
^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.