Home > Software design >  Regex to hide first two IP address octets
Regex to hide first two IP address octets

Time:01-06

I have gotten to the following regex command to 'x' the first two octets of IP addresses, using powershell;

-Replace '(?=\d{1,3}\.\d{1,3}\.)\d', 'x'

On the following dataset;

10.101.11.11
101.11.11.11
2003.12.11

I get;

xx.xxx.11.11
xxx.xx.11.11
2xxx.12.11

It formats the IP addresses correctly as required but I can't seem to get it to ignore dates with . in them

CodePudding user response:

You can use

(?:\G(?!^)|\b)\d(?=\d{0,2}\.\d{1,3}\.)

See the regex demo. Details:

  • (?:\G(?!^)|\b) - word boundary or the end of the previous successful match
  • \d - a digit
  • (?=\d{0,2}\.\d{1,3}\.) - a position that is immediately followed with zero to two digits . one to three digits ..

CodePudding user response:

Try this regex:

-Replace '\d{1,3}\.\d{1,3}.(\d{1,3}.\d{1,3})



Write-Host $('2023.12.12' -Replace '\d{1,3}\.\d{1,3}.(\d{1,3}.\d{1,3})', 'xxx.xxx.$1')
2023.12.12

Write-Host $('202.21.32.1' -Replace '\d{1,3}\.\d{1,3}.(\d{1,3}.\d{1,3})', 'xxx.xxx.$1')
xxx.xxx.32.1
  • Related