javascript.netregexmaui

Validating Thickness (Margin/Padding) string using Regex for different platforms


I have a specific Regex pattern requirement for a string pattern which contains margin/padding (Thickness) for max 3 different platform and devices separated by semicolon. Margin and Padding format is for .NET MAUI where you can have Universal, Horizontal/Vertical, LTRB.

Comma separated is Thickness (Margin) and semicolon separator is for different devices/platforms. Note that end of string shouldn't end with comma or semicolon.

Should Match (spaces are intentional for visibility)

Shouldn't Match (spaces are intentional for visibility)

Tried this myself, but couldn't achieve above.

^((?:\d{1,3},?){1,4};?){1,3}$


Solution

  • This is probably an additional way.

    ^(?!.*\d{4})(?:(?:^|;)\d+(?:,\d+){0,3}){1,3}$
    

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

    ^ 
    (?! .* \d{4} )               # No 4 or more digits
    (?:
       (?: ^ | ; )               # BOS or device separator
       \d+ (?: , \d+ ){0,3}      # 1-4 Margins
    ){1,3}                       # 1-3 Devices
    $ 
    

    Info on the Guard assertion used:

    Margin is digits and allowed 1-3 digits per margin. Allowed margins per device is 1-4. The margin regex can be expressed then as \d{1,3} (?: , \d{1,3} ){0,3} where this represents 1-4 margins.

    The valid digits are quantified as \d{1,3} allowed in a group. Doing the math, there can not be 4 or more digits. The digits can then be refactored by setting an assertion at the beginning of the string that finds a group of 4 digits. If found the string is invalid. If not, any digits found are controlled
    by simple quantifiers + of * where no block is greater than 3 digits.

    This allows to convert \d{1,3} into \d+ which is much more efficient.