n_kips
n_kips

Reputation: 585

How to write regex to enforce maximum of 255 characters?

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}$

Upvotes: 4

Views: 7446

Answers (2)

Kobi
Kobi

Reputation: 138117

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).

Upvotes: 8

red-X
red-X

Reputation: 5138

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}$

Upvotes: 3

Related Questions