Limiting RegEx to match only a string of 1-254 characters length

This is my RegEx:

"^[^\.]([\w-\!\#\$\%\&\'\*\+\-\/\=\`\{\|\}\~\?\^]+)([\.]{0,1})([\w-\!\#\$\%\&\'\*\+\-\/\=\`\{\|\}\~\?\^]+)[^\.]@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$"

I need to match only strings less than 255 characters.

I've tried adding the word boundaries at the start of the RegEx but it fails:

"^(?=.{1,254})[^\.]([\w-\!\#\$\%\&\'\*\+\-\/\=\`\{\|\}\~\?\^]+)([\.]{0,1})([\w-\!\#\$\%\&\'\*\+\-\/\=\`\{\|\}\~\?\^]+)[^\.]@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$"

Answers


You need the $ in the lookahead to make sure it's only up to 254. Otherwise, the lookahead will match even when there are more than 254.

(?=.{1,254}$)

Also, keep in mind that you can greatly simplify your regex because many characters that would usually need to be escaped do not need to when in a character class (square brackets).

"[\w-\!\#\$\%\&\'\*\+\-\/\=\`\{\|\}\~\?\^]"

is the same as this:

"[-\w!#$%&'*+/=`{|}~?^]"

Note that the dash must be first in the character class to be a literal dash, and the caret must not be first.

With some other simplifications, here is the complete string:

"^(?=.{1,254}$)[-\w!#$%&'*+/=`{|}~?^]+(\.[-\w!#$%&'*+/=`{|}~?^]+)*@((\d{1,3}\.){3}\d{1,3}|([-\w]+\.)+[a-zA-Z]{2,6})$"

Notes:

  • I removed the stipulation that the first char shouldn't be a period ([^.]) because the next character class doesn't match a period anyway, so it's redundant.
  • I removed many extraneous parens
  • I replaced [0-9] with \d
  • I replaced {0,1} with the shorthand "?"
  • After the @ sign, it seemed that you were trying to match an IP address or text domain name, so I separated them more so it couldn't be a combination
  • I'm not sure what the optional square bracket at the end was for, so I removed it: "(]?)"

I tried it in Regex Hero, and it works. See if it works for you.


Need Your Help

How to get bash files to render php constants?

php shell ubuntu

Does anyone know how to get bash files to render php constants? For example if i create a php file containing,

How to publish content to Facebook from a Windows Phone 7 device

facebook windows-phone-7

I'm writing a Windows Phone 7 App and would like to be able to push content from my app to the users facebook profile, comments, pictures etc. I have started reading the documentation but it all t...