TAGS :Viewed: 2 - Published at: a few seconds ago

[ Regex.Replace for IP address ]

I've lifted a piece of code from somewhere on the internet it looks like this

 ip = Regex.Replace(ip, @"^(?<Prefix>(\d{1,3}\.){3})\d{1,3}$", "${Prefix}*");

What it does is takes an IP address and replaces the last section with a asterisk. For example would become 192.168.0.*

I'm useless with RegEx, I've tried to understand what the above is actually doing, but not having any success.

What I'm after is 2 more Regex.Replace code so that becomes

  • 192.168.*.*
  • 192.*.*.*

Can anyone help me?

Answer 1

192.168.*.* = ip = Regex.Replace(ip, @"^(?<Prefix>(\d{1,3}\.){2})\d{1,3}\.\d{1,3}$", "${Prefix}*.*");

192.*.*.* = ip = Regex.Replace(ip, @"^(?<Prefix>(\d{1,3}\.))\d{1,3}\.\d{1,3}\.\d{1,3}$", "${Prefix}*.*.*");

Give that a shot, see what happens.