Here I say minimum 1 o and maximum three o but here I have more then three
o and this expression give true but
it should give false according to me ?
bool status = Regex.IsMatch("foooooood", "o{1,3}");
The main problem is that you're not understanding how the {m,n} qualifier
works. Specifically, you're reading too much into its abilities. You
shouldn't think of {m,n} as meaning "AT LEAST m occurrences and AT MOST n
occurrences" but rather "FROM m TO n occurrences." The difference is subtle
but important. The first phrase suggests that there must be some limitation
of the letter "o" in your regex above, which is how you were interpreting
it. The second just says "as long as I can find anywhere from 1 to 3 o's,
I'm happy." And the regex engine can definitely find from 1 to 3 o's. In
fact, it can do it three times: 2 sets of 3 and 1 single o.
In order to do what you thought it would do, your best bet is to use an
advanced regex technique called lookaround. Lookaround allows you to look at
characters before your intended match or after it and require that a pattern
either be present or absent. Requiring a pattern to be present is called
positive lookaround, while requiring it to be absent is negative lookaround.
Actually, you don't usually say "lookaround" but rather you indicate the
direction, so you can have positive or negative lookbehind (searching for a
pattern before your match pattern) and positive and negative lookahead
(searching for a pattern after your match pattern).
To get 3 and only 3 o's, you'd need to both look behind and look ahead to
make sure that there isn't a 4th o either before or after your pattern. The
regex would look like this:
(?<!o)o{1,3}(?!o)
This WILL find matches in the following input:
fod
food
foood
Zoo
to
oops
hotfoot
It will NOT find matches in this input:
foooooood
Zooool
ooooooh! aaaaah!