Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exclude zero length regex matches from my results? [duplicate]

Tags:

regex

I did a quick google search and could not find any results. * and ? include zero length matches. How can I exclude them from my results?

For example running a? on "ada" returns a zero length match at 1 and 3. How can I exclude them?

like image 466
white_tree Avatar asked Oct 16 '25 11:10

white_tree


1 Answers

This is a very generic question that I'd rather solve on a case-by-case basis; but one option that always works (as long as you have lookahead available - you didn't specify the regexp dialect) is to prepend (?=.) to the regexp. /(?=.)a?/ is functionally equivalent to /a/; /(?=.)a*/ is functionally equivalent to /a+/, and to /aa*/.

Thus, the examples in your question don't really make sense - you'd never write /(?=.)a?/ since /a/ is both syntactically and conceptually simpler. Therefore this is basically an XY-question - it would have been better to ask your real use-case, since it is a moot issue with /a?/ and /a*/.

like image 176
Amadan Avatar answered Oct 19 '25 05:10

Amadan