Reputation: 1191
I have some regular expression like that:
(\d+\.)+
it's implement strings like 1.234.2421.222.11 Can i restrict max length of whole string (not quantity of groups)?
thanks a lot
Upvotes: 3
Views: 1966
Reputation: 170148
Note that (\d+\.)+
does not match 1.234.2421.222.11
in it's entire. Your pattern mandates it should end with a .
. You probably want a pattern like this:
\d+(\.\d+)*
And to give the input string a max length, say a max of 15 chars, do something like this:
^(?=.{0,15}$)\d+(\.\d+)*$
assuming your regex implementation supports look aheads.
Okay, if your regex implementation does not support look aheads, do it in two steps. Something like this (pseudo code):
if input matches ^\d+(\.\d+)*$ and ^.{0,15}$ do
....
end
or, as paxdiablo also mentioned, use your programming language's built-in function to get the length of the string.
Upvotes: 7
Reputation: 881153
If your regex engine supports lookaheads, you can use something like:
^(?=.{M,N}$)(\d+\.)*\d+$
(fixed to not require a trailing .
character) and this embeds the length check within the same regex. You need to replace M
and N
with the minimum and maximum size respectively.
If your engine is not so modern as to have lookaheads, you need to do two regex chacks:
^.{M,N}$
^(\d+\.)*\d+$
and ensure it passes them both. The first is the length check, the second is the content check.
But you may find that a regex is overkill for the length check, it's probably easier just to check the string length with Length()
.
Upvotes: 4