I need to modify the exp:
/^[-\p{L}\d]+$/u
The purpose is to allow maximum 3 digits in whole string, but letter chars and dashes should be allowed without quantity restrictions. No matters where digits are located within string. For instance:
test345 //this should match
345te-st //this should match
3454dtest //this shouldn\'t match
I have already tried some patterns, but is don't work properly:
/^[-\p{L}\d{0,3}]+$/u
/^[-\p{L}]+[\d]{0,3}+$/u
/^([-\p{L}]+)([\d]+){0,3}$/u
The patterns that you tried don't work properly matching max 3 digits anywhere in the string because between the start and end anchors:
[-\p{L}\d{0,3}]+ which matches repeating 1+ times any of the listed characters between [...] (So there is no digit limit due to the +)[-\p{L}]+[\d]{0,3}+ matches 1+ times [-\p{L}] followed by 0-3 consecutive digits (So the digits can not be at the start for example)([-\p{L}]+)([\d]+){0,3} uses 2 capture groups, but the order here is also 1+ times [-\p{L}] and 0-3 consecutive digits (only here is the capture group repeated)If empty strings are also allowed:
^(?:[\p{L}-]*\d){0,3}[\p{L}-]*$
^ Start of string(?:[\p{L}-]*\d){0,3} Match 0-3 times optional repetitions of [\p{L}-] and a single digit[\p{L}-]* Match optional repetitions of [\p{L}-] at the end$ End of stringElse you can assert that the string is not empty using (?!$)
^(?!$)(?:[\p{L}-]*\d){0,3}[\p{L}-]*$