Search code examples
regexlogic

How to make the right mask?


I'm checking valid strings for "Invalid format".

The minimum length of the string is 5 characters, the maximum is 32 (/[a-z\d_\.]{5,32}/).

The "Invalid format" error occurs. It occurs if the string:

  1. Starts with three or more digits (one or two digits are acceptable);
  2. It starts and ends with the _ character;
  3. Contains a dot after which there are less than four characters starting with the letter.

I wrote an expression that works for the first two conditions, but I don't understand how to implement the third condition? If possible, then give an example of a separate expression, I do not understand exactly how to do it with the dot symbol.

^(?!(?:_|\d{3,}))[a-z\d_\.]{5,32}(?<!_)$

https://regex101.com/r/W9njMe/1

Thanks.


Solution

  • You might use a pattern with an assertion, that does not match a dot after the last occurence of [a-z] when there are 1-4 chars left till the end of the string.

    ^(?!_|\d{3})(?!.*[a-z](?=.{1,4}$)[a-z\d_]*\.)[a-z\d_.]{5,32}$(?<!_)
    

    Explanation

    • ^ Start of string
    • (?!_|\d{3}) Assert not _ or 3 digits
    • (?! Negative lookahead, assert what is to the right is not
      • .*[a-z] Match the last occurrence of [a-z]
      • (?=.{1,4}$) Assert 1-4 chars till end of string
      • [a-z\d_]*\. Match match a .
    • ) Close lookahead
    • [a-z\d_.]{5,32}$ Match 5-32 chars in the string
    • (?<!_) Assert not _ to the left

    Regex demo