'Regex to validate alphanumeric, underscores and hyphens with no spaces and only 40 characters

I wanted to know how I can specify character count for my regex. I have the correct regex, I only need to make sure this will work validating zero to fourty characters.

here is the regex

$fnameRegex = "/^[a-zA-Z0-9{0,40}-_]+$/";

i might have put the {0,40} in the wrong place.



Solution 1:[1]

try [a-zA-Z0-9]{40} this will check 40 characters of alpha numeric with upper and lower case

Solution 2:[2]

What about this?

^(\d){0,40}$

\d matches only digits {0,40} indicates that the previous expression (\d) can be present from 0 to 40 times.

You can use this tool to check your regex. It can be useful: http://gskinner.com/RegExr/

Hope this helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bikash Shrestha
Solution 2 Jair Reina