1

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}

http://regexstorm.net/tester

An Overflowed Stack
  • 334
  • 1
  • 5
  • 20

4 Answers4

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

https://regex101.com/r/cZ0sD2/11

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
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?

Community
  • 1
  • 1
TVOHM
  • 2,740
  • 1
  • 19
  • 29