Need help creating a regular expression to match a specific string (example inside)

I am working on a program where I need to match a regular expression and a string. The line is pretty simple actually, but I have problems with the current regex (I use the .net regex engine)

My current regular expression is: "^ [VvEeTtPp] [^ a-zA-Z0-9 \ s] \ d {0.12}? $"

Now the line I want to match always follows this pattern

  • First one letter (only letters are allowed: V, E, P, T in any case)
  • Then dash
  • Finally, from 4 to 12 digits.

There is a final restriction that the regular expression must match any substring that matches the rules (for example, "V" or "E-" or "P-123")

The regular expression works quite well, but it takes things like "V -".

Can someone help me write a better expression?

thanks

+3
source share
5 answers

Well, the substring of rule 4-12 does make it rule 1-12, so what about:

        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
source

This should do it:

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

Edit:
You can also select substrings such as "P-123", "-123" and "123":

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

Edit 2:
Added a positive lookahead at the beginning, so the pattern does not match the substring "". Although this is a valid substring of legal value, I assume that you do not want a particular substring ...

+3
source

[VvEePpTt] -\{d} 4,12

+1

, ?

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

It will accept one character from those that are indicated behind it either by nothing, not a single dash, which, in turn, should not contain 4-12 digits, or 4-12 digits and corresponds to them. For example:

  • IN
  • ** AT 12
  • At 12
  • V-12345
  • P-123456789012 3

EDIT: $ added at the end so that it doesn’t work if the string contains extra characters

+1
source

I think this template meets the specification.

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

Breakdown of the structure:

^             - 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
+1
source

Source: https://habr.com/ru/post/1715943/


All Articles