需要帮助来构建正则表达式以匹配特定字符串(示例内部)

时间:2009-08-24 22:24:43

标签: .net regex

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

我当前的正则表达式是“^ [VvEeTtPp] [^ a-zA-Z0-9 \ s] \ d {0,12}?$”

现在,我要匹配的字符串始终遵循此模式

  1. 首先是一个字母(在任何一种情况下只允许使用V,E,P,T字母)
  2. 然后,破折号
  3. 最后是4到12位。
  4. 最后一个限制是正则表达式必须匹配符合规则的任何子字符串(例如“V”或“E-”或“P-123”)

    正则表达式工作得相当好,但它会接受像“V - ”这样的东西。

    有人可以帮我写一个更好的表达吗?

    由于

5 个答案:

答案 0 :(得分:3)

这应该这样做:

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

编辑:
要匹配像“P-123”,“ - 123”和“123”这样的子串:

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

编辑2:
在开头添加了一个正向前瞻,因此模式与子串“”不匹配。虽然这是合法值的有效子字符串,但我假设您不需要特定的子字符串...

答案 1 :(得分:2)

嗯,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 :(得分:1)

[VvEePpTt] - \ d {4,12}

答案 3 :(得分:1)

你可以尝试一下,告诉我它是否有效吗?

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

它将接受指定的单个字符,后跟任何一个或一个短划线,而后者不是后跟4-12位数字或4-12位数字并匹配它们。例如:

  • V
  • ** N - ** 12
  • V 12
  • V-12345
  • P-123456789012 3

编辑:最后添加$,如果字符串包含任何额外字符,则会失败

答案 4 :(得分:1)

我认为这种模式符合规范。

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