代码之家  ›  专栏  ›  技术社区  ›  Carlos G.

需要帮助以生成与特定字符串匹配的正则表达式(内部示例)

  •  3
  • Carlos G.  · 技术社区  · 15 年前

    我正在开发一个程序,需要在其中匹配正则表达式和字符串。实际上,字符串非常简单,但我当前的regex有问题(我使用的是.NET regex引擎)

    我当前的正则表达式是“^[vveetpp][^a-za-z0-9\s]\d 0,12?”$

    现在,我想要匹配的字符串总是遵循这个模式

    1. 首先是一个字母(在任何情况下,只允许字母V、E、P、T)
    2. 然后,一个破折号
    3. 最后从4到12位数字。

    最后一个限制是regex必须匹配符合规则的任何子字符串(例如“v”或“e-”或“p-123”)。

    regex工作得相当好,但它会接受“v--”之类的东西。

    有人能帮我写一个更好的表达方式吗??

    谢谢

    5 回复  |  直到 15 年前
        1
  •  2
  •   Marc Gravell    15 年前

    好吧,4-12规则的子字符串实际上使其成为1-12规则,那么如何:

            Regex re = new Regex(@"^[VvEeTtPp](-|-[0-9]{1,12})?$");
            Console.WriteLine(re.IsMatch("B"));
            Console.WriteLine(re.IsMatch("V"));
            Console.WriteLine(re.IsMatch("E-"));
            Console.WriteLine(re.IsMatch("P-123"));
            Console.WriteLine(re.IsMatch("V--"));
    
        2
  •  3
  •   Guffa    15 年前

    应该这样做:

    ^[EPTVeptv](-(\d{4,12})?)?$
    

    编辑:
    还要匹配“P-123”、“-123”和“123”等子字符串:

    ^(?=.)[EPTVeptv]?(-\d{,12})?$
    

    编辑2:
    在开头添加了一个正的lookahead,以便模式与子字符串“”不匹配。虽然这是一个合法值的有效子字符串,但我假定您不希望使用特定的子字符串…

        3
  •  1
  •   Elieder    15 年前

    [vveeptt]—\d 4,12

        4
  •  1
  •   Savvas Dalkitsis    15 年前

    你能试试这个告诉我它是否有效吗?

    ^[VvEeTtPp](-(\d{4,12}){0,1}){0,1}$
    

    它将接受指定字符的单个字符,后跟“无”或“一个短划线”,后者依次不后跟4-12位或4-12位,并与它们匹配。例如:

    • **V-** 12
    • 十二
    • V-12345
    • P 12345 67 89012

    编辑:在末尾添加了一个$以便在字符串包含任何额外字符时失败。

        5
  •  1
  •   Fredrik Mörk    15 年前

    我认为这个式样符合规格。

    string pattern = @"^[VvEePpTt](?:$|-(?:$|\d{1,12}$))";
    // these are matches
    Console.WriteLine(Regex.IsMatch("V", pattern));
    Console.WriteLine(Regex.IsMatch("v-", pattern));
    Console.WriteLine(Regex.IsMatch("P-123", pattern));
    Console.WriteLine(Regex.IsMatch("t-012345678901", pattern));
    // these are not
    Console.WriteLine(Regex.IsMatch("t--", pattern));
    Console.WriteLine(Regex.IsMatch("E-0123456789012", pattern));
    

    模式分解:

    ^             - start of string
    [VvEePpTt]    - any of the given characters, exactly once
    (?:           - start a non-capturing group...
    $|-           - ...that matches either the end of the string or exactly one hyphen
    (?:           - start a new non-capturing group...
    $|\d{1,12}$   - that matches either the end of the string or 1 to 12 decimal digits
    ))            - end the groups