Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write regex to enforce maximum of 255 characters?

Tags:

regex

What regular expression would match any characters (including spaces), but have a maximum of 255 characters? Is this it?

^[a-zA-Z0-9._]{1,255}$
like image 948
n_kips Avatar asked Oct 20 '25 17:10

n_kips


2 Answers

Well, anything would be:

^.{1,255}$

. doesn't allow new lines. If that's a problem, you can use the dot-all flag (usually /s).

If you want to add spaces to your regex, try this (note the space):

  • ^[a-zA-Z0-9._ \t]{1,255}$ - Allow spaces and tabs.
  • ^[a-zA-Z0-9._\s]{1,255}$ - Allow all whitespaces.
  • ^[\s\w.]{1,255}$ - Same as the above (unless your flavor supports Unicode).
like image 88
Kobi Avatar answered Oct 23 '25 06:10

Kobi


Well that would not allow anything, if you want anything, you're better off using ^.{1,255}$.

Or, if you want to allow nothing as well: ^.{0,255}$

like image 45
red-X Avatar answered Oct 23 '25 08:10

red-X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!