Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to understand the following regular expression quantifier (a is just an exemplary token here):

a{n}?

How does the question mark affect the match of the above expression? And how does it differ from the following?

a{n}

I would have expected the pattern aa{1}?a to match both aaa and aa for example. While it matches aaa, aa is not a match. The pattern a(a{1})?a does match both, so the parentheses do make a difference here.


Note: The msdn article Quantifiers in Regular Expressions states for both:

The {n} quantifier matches the preceding element exactly n times, where n is any integer.

For {n}?, it adds the following, not overly helpful part:

It is the lazy counterpart of the greedy quantifier {n}+.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

Nothing. The article states:

The {n} quantifier matches the preceding element exactly n times, where n is any integer. {n} is a greedy quantifier whose lazy equivalent is {n}?.

The {n}? quantifier matches the preceding element exactly n times, where n is any integer. It is the lazy counterpart of the greedy quantifier {n}+.

Notice the text is exactly the same. Basically, adding ? does not change the behavior of the quantifier. It appears that .NET's regular expression engine supports {n}? as a alternative to {n}.


Interestingly, this article does appear to contain an error:

The {n,} quantifier matches the preceding element at least n times, where n is any integer. {n,} is a greedy quantifier whose lazy equivalent is {n}?.

This is wrong. The lazy equivalent of {n,} is {n,}? which is not the same as {n}?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...