Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding "Max Length" to Regex

Tags:

c#

regex

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})(\]?)}

like image 260
SeToY Avatar asked Dec 17 '12 22:12

SeToY


2 Answers

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.

like image 131
Firas Dib Avatar answered Sep 19 '22 17:09

Firas Dib


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.

like image 32
Zeki Avatar answered Sep 19 '22 17:09

Zeki