How can I extend already present Regex's with an attribute telling that the regex can't exceed a maximum length of (let's say) 255?
I've got the following regex:
([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)
I've tried it like that, but failed:
{.,255([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)}
Best way of doing this, if it has to be a solely regex based solution, would be to use lookarounds.
View this example: http://regex101.com/r/yM3vL0
What I am doing here is only matching strings that are at most three characters long. Granted, for my example, this is not the best way to do it. But ignore that, I'm just trying to show an example that will work for you.
You also have to anchor your pattern, otherwise the engine will just ignore the lookaround (do I have to explain this in depth?)
In other words, you can use the following in your regular expression to limit it to at most 255 characters:
^(?!^.{256})([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)
I also feel it is my duty to tell you your regular expression is bad and you should feel bad.
A regex is not really made to solve all problems. In this case, I'd suggest that testing a length of 255 is going to be expensive because that's going to require 255 states in the underlying representation. Instead, just test the length of the string separately.
But if you really must, you will need to make your characters optional, so something like:
.?{255}
Will match any string of 255 or fewer characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With