在 C# 正则表达式中,字符串至少包含一个但不超过 2 个字母“n”

本文关键字:不超过 包含一 正则表达式 字符串 | 更新日期: 2023-09-27 18:31:54

给定一个字符串,当字符串在任何位置至少包含一个但不超过 2 个字母"n"时,我如何编写匹配的正则表达式?到目前为止,我只提出了n{1,2}

http://regexstorm.net/tester

在 C# 正则表达式中,字符串至少包含一个但不超过 2 个字母“n”

我会使用:

 ^[^n]*n[^n]*n?[^n]*$

其中 [^n]* 代表 0 或更多 NON n

它将匹配至少一个n和最多 2 个n

根据评论,您可以使用:

^(?:[^n]*n[^n]*){1,2}$

您可以将{1,2}更改为{3,5}或任何您想要的内容。

^(?!(?:.*n){3}).*n.*$

您可以为相同的lookahead添加。请参阅演示。

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

^(?!(?:[^'nn]*n){3}).*n.*$

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

为什么要

使用正则表达式?这很难在高度可保留和灵活的扩展方法中实现。

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;
}

另一个示例正则表达式,改编自此答案,将为您提供 1 或两次出现的字符的匹配。

"^([^n]*n){1,2}[^n]*$"

有没有理由不能像InMiddle建议的那样用简单的方法解决这个问题?