Search code examples
phpregexlaravelpcre

MasterFormat Classification Regex


I need a recipe for validating a MasterFormat classification string that consists of a set of numbers followed by a title string.

The numbers that begin the string must be:

3 sets of 2 digits separated by spaces:

09 68 13

The last set of digits can also be a decimal:

09 68 13.36

Followed by a space

Then a string of words to represent the title, the first letter of each word to caps

09 68 13 Tile Carpeting

09 68 13.36 Tile Carpeting

I have a start which seems to work but I can't seem to get the word string added in correctly.

\d{2}\s\d{2}\s\d{2}(\.\d{2}){0,1}

This will be validated in a Laravel Rule.


Solution

  • You may use

    ^\d{2}\s\d{2}\s\d{2}(?:\.\d{2})?\s+\p{Lu}\p{L}*(?:\s+\p{Lu}\p{L}*)*\s*$
    

    See the regex demo. Details:

    • ^ - start of string
    • \d{2}\s\d{2}\s\d{2} - two digits, whitespace, two digits, whitespace, two digits
    • (?:\.\d{2})? - an optional non-capturing group matching 1 or 0 occurrences of a . and then two digits
    • \s+ - 1+ whitespaces
    • \p{Lu}\p{L}* - an uppercase letter followed with 0+ letters
    • (?:\s+\p{Lu}\p{L}*)* - 0 or more occurrences of 1+ whitespaces followed with an uppercase letter followed with 0+ letters
    • \s* - 0+ whitespaces
    • $ - end of string.