Given a string, how could I write a regular expression that matches when the string contains at least one but no more than 2 letters "n" at any position? So far, I only came up with n{1,2}
Asked
Active
Viewed 702 times
1
-
1And what is wrong with `n{1,2}`? – Frédéric Hamidi Jan 26 '16 at 17:31
-
2"aanaanffnnnn" Try this – An Overflowed Stack Jan 26 '16 at 17:34
-
And why does it need to be a regular expression? An extension method `bool ContainsMoreThanAndLessThan(this string s, char c, int minOcurrences, int maxOccurences)` is trivial and much more flexible. – InBetween Jan 26 '16 at 17:46
4 Answers
3
I'd use:
^[^n]*n[^n]*n?[^n]*$
Where [^n]*
stands for 0 or more NON n
It will match at least one n
and at most 2 n
According to comment, you could use:
^(?:[^n]*n[^n]*){1,2}$
You can change {1,2}
into {3,5}
or anything you want.

Toto
- 89,455
- 62
- 89
- 125
-
Thank you for your answer. It works, but is there a better way to do it? The ideal solution I wish to have is that by simply changing two numbers in the regex, i would be able to change the occurrences. – An Overflowed Stack Jan 26 '16 at 17:43
-
-
1
^(?!(?:.*n){3}).*n.*$
You can add a lookahead
for the same.See demo.
https://regex101.com/r/cZ0sD2/10
or
^(?!(?:[^\nn]*n){3}).*n.*$

vks
- 67,027
- 10
- 91
- 124
0
Why use Regex at all? This is trival to implement in an extension method that is highly mantainable and flexible.
public static bool ContainsMoreThanAndLessThan(this string s, char c, int maxOcurrences, int minOcurrences)
{
Debug.Assert(maxOcurrences >= minOcurrences);
Debug.Assert(minOcurrences > 0);
Debug.Assert(s != null);
if (s.Length < minOcurrences)
{
return false;
}
var ocurrences = 0;
foreach (var ch in s)
{
if (ch == c)
{
ocurrences++;
}
if (ocurrences > maxOcurrences)
{
return false;
}
}
return ocurrences >= minOcurrences;
}

InBetween
- 32,319
- 3
- 50
- 90
-
Because this is a practice assignment on regular expression. :( – An Overflowed Stack Jan 26 '16 at 17:57
-
0
Another example Regex, adapted from this answer, will give you a match on 1 or two occurrences of the character.
"^([^n]*n){1,2}[^n]*$"
Is there a reason this cannot be solved with a simple method as InBetween suggests?