4

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?

white_tree
  • 978
  • 1
  • 11
  • 11

1 Answers1

2

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*/.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I am using java's util classes. I don't know if that helps. I am pretty sure lookahead is available. I think I got it, thank you! – white_tree Jul 28 '15 at 04:07
  • 2
    It is; so `(?=.)` trick should work. But my point is that it it is usually not necessary: if you don't want a zero-match on `/a?/`, then `?` should not be there. It's like putting chicken wings in your chocolate glaze, then trying to figure out how to get rid of the taste of meat in it; you probably shouldn't have put chicken in your chocolate in the first place. (Of course, there's legitimate chocolate chicken recipes; but most people aren't making those, and don't want chicken in their chocolate.) :D – Amadan Jul 28 '15 at 04:12
  • Yes, understood, sorry, now I feel silly :) – white_tree Jul 28 '15 at 04:14
  • No worries :D Sorry, I tend to pluck out silly comparisons all the time. No insult intended. – Amadan Jul 28 '15 at 04:16