Search code examples
ruby-on-railsregexgsubipv4

Rails: Dynamically convert last quartet of IPv4 address to wildcard


I am looking for the regex/gsub combination to do below for any number in the last quartet.

irb(main):008:0> ip = "192.168.1.255"
=> "192.168.1.255"
irb(main):009:0> ip.gsub("255", "*")
=> "192.168.1.*"

Solution

  • Does something like this meet your needs?

    ip.sub(/^([0-9]+\.[0-9]+\.[0-9]+\.)[0-9]+/, $1 + '*' )
    

    or better...

    ip.sub(/^([0-9]+\.){3}[0-9]+/, $1 + '*' )
    

    or better still...

    ip.sub(/\d+$/, '*')