Regexp to normalize (pad with zeros) IP addresses

I have a copy of a log file that I want to simplify for viewing / editing.
I use the text panel to remove unnecessary things, and I can enter a regular expression as a search term and use \ 1. \ 2. \ 3. \ 4 in the target field for the captured groups.
I would like to change all the IPs that run each line from

[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} 

to

 [0-9]{3}\.[0-9]{3}\.[0-9]{3}\.[0-9]{3} 

with simple leading zeros. How to do it in one go?

Input Example:

 10.2.123.4 110.12.23.40 123.123.123.123 1.2.3.4 

Output example

 010.002.123.004 110.012.023.040 123.123.123.123 001.002.003.004 

See my own answer for what works

Thanks for your input.

+4
source share
3 answers

Not quite complete, one liner you want, but it at least wraps it on two lines instead of the current 8.

Following the same formatting you used in your answer:

 ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}) -> 00\1.00\2.00\3.00\4 ^0*([0-9]{3})\.0*([0-9]{3})\.0*([0-9]{3})\.0*([0-9]{3}) -> \1.\2.\3.\4 

How it works:

  • it fills all the numbers so that each section has at least 3 numbers.
  • he pulls out exactly 3 numbers from each section and ignores any leading "0 remaining
+2
source

Ok, I decided to do it in a few minutes. I post it here for future reference or in case someone comes up with one regex

Note that each search has a finite space, and each one replaces

 ^([0-9]{1})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}) -> 00\1.\2.\3.\4 ^([0-9]{2})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}) -> 0\1.\2.\3.\4 ^([0-9]{3})\.([0-9]{1})\.([0-9]{1,3})\.([0-9]{1,3}) -> \1.00\2.\3.\4 ^([0-9]{3})\.([0-9]{2})\.([0-9]{1,3})\.([0-9]{1,3}) -> \1.0\2.\3.\4 ^([0-9]{3})\.([0-9]{3})\.([0-9]{1})\.([0-9]{1,3}) -> \1.\2.00\3.\4 ^([0-9]{3})\.([0-9]{3})\.([0-9]{2})\.([0-9]{1,3}) -> \1.\2.0\3.\4 ^([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{1}) -> \1.\2.\3.00\4 ^([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{2}) -> \1.\2.\3.0\4 

Text Panel Syntax:

 ^\([0-9]\{1\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\) -> 00\1.\2.\3.\4 ^\([0-9]\{2\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\) -> 0\1.\2.\3.\4 ^\([0-9]\{3\}\)\.\([0-9]\{1\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\) -> \1.00\2.\3.\4 ^\([0-9]\{3\}\)\.\([0-9]\{2\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\) -> \1.0\2.\3.\4 ^\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{1\}\)\.\([0-9]\{1,3\}\) -> \1.\2.00\3.\4 ^\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{2\}\)\.\([0-9]\{1,3\}\) -> \1.\2.0\3.\4 ^\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{1\}\) -> \1.\2.\3.00\4 ^\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{3\}\)\.\([0-9]\{2\}\) -> \1.\2.\3.0\4 
+2
source

I don’t give a damn about "." pave, connect. No need for regular expression. Regex won't even do any good.

JavaScript, for example:

 var ip = "110.12.23.40"; ip = ip.split(".").map( function(i) { return ("00"+i).slice(-3); }).join("."); alert(ip); // 110.012.023.040 
+1
source

All Articles