regexp maximal length restrict

2020-07-22 09:56发布

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

标签: regex
2条回答
神经病院院长
2楼-- · 2020-07-22 10:38

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.

EDIT

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.

查看更多
Ridiculous、
3楼-- · 2020-07-22 10:48

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

查看更多
登录 后发表回答