Reluctant quantifiers can be very useful. However, I can't think of any use of ??
, the reluctant version of ?
. Can somebody give me an example, or is it just there because the other quantifiers have reluctant versions too?
views:
132answers:
3One example - that might not be that useful in practice, but could give you an idea of how it can be used (excuse the c# syntax):
Match username = Regex.Match(input, @"^([\w\W]*?)(@[\w\W]+\.[\w\W])??$");
Now, what this will do is that the user enters his user name or email address in an input form, and if an email address was entered the regex grabs only the part before the @
. That way more than one type of input is OK, and you still get the same data out of it regardless if the @domain.com
was supplied or not.
Disclaimer: This is not a regex that I would use as is for said purpose - it matches way too many non-email adresses too. But hey, it's a demo... ;)
Maybe possibly if you wanted something in a different capturing group than it otherwise would be. I can't recall ever seeing it, and can't think of an example that wouldn't be highly contrived.
Here’s an example regular expression that uses the ??
quantifier:
(?:\w+-??|-\w+)
It matches every word that’s either followed by a hyphen or preceeded by a hyphen. In foo-bar
it would then match foo
and -bar
rather than foo-
and bar
as (?:\w+-?|-\w+)
would.