Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust regex to also match partial expression

Tags:

regex

Is there a generic way to wrap an existing regex to also accept partial matches?

For example verifying an IPV4 address one can use ((?:(?:25[0-5]|2[0-4]\d|1?\d{1,2})(?:\.(?!$)|$)){4})

Now this works for

  • 10.0.10.1

But not for

  • 1
  • 10
  • 10.0
  • 10.0.
  • 10.0.1
  • 10.0.10
  • 10.0.10.

I want to provide a generic way to wrap the existing regex (or any else) without modifying it into a new regex that accepts any amount of partial ip addresses.

UPDATE: The intention of this is to use it as a mask for a text field thus I need to allow partial strings otherwise it would only work by inserting the complete IP at once e.g. via pasting from clipboard.

like image 877
hypnomaki Avatar asked Oct 19 '25 14:10

hypnomaki


1 Answers

I suggest:

^(?:\b\.?(?:1\d{0,2}|[3-9]\d?|2(?:[0-4]\d?|5[0-5]?|[6-9])?|0|$)){0,4}$

demo

Feel free to change the last quantifier to {1,4} if you do not want the empty string to be valid.

Notices:

  • consecutive dots are avoided using a word-boundary at the start of the main group.
  • this word-boundary also avoids a dot at the start the field.
  • about the group that contains numbers description:
    • branches are ordered by probability of the starting digit (111 numbers start with 1, 77 start with [3-9], etc.)
    • the last branch is the end of the string anchor $ to allow a trailing dot. It is more efficient to do that and less problematic than making the whole group optional
like image 192
Casimir et Hippolyte Avatar answered Oct 21 '25 02:10

Casimir et Hippolyte