Reputation: 5882
Here's my sample data:
192.168.1.1
192.168.1.11
In bash, I could simply do cat file.txt | grep -w 192.168.1.1
and it will only grab 192.168.1.1, not 192.168.1.11
However, in Ruby, when I'm trying to replace 192.168.1.1
, it actually replaces 192.168.1.11
as well. Here's what I'm doing:
replace_array = ['192.168.1.1','x','xx','xx]
replace_array.each {|s| data.gsub!(/#{s}/i, "[redacted]")}
but this leaves 192.168.1.11
looking like [redacted]1
as shown in the example below:
2.5.8 :005 > replace_array = ["192.168.1.1","x","xx","xxx"]
=> ["192.168.1.1", "x", "xx", "xxx"]
2.5.8 :006 > data = "192.168.1.1\n192.168.1.11"
=> "192.168.1.1\n192.168.1.11"
2.5.8 :007 > replace_array.each {|s| data.gsub!(/#{s}/i, "[redacted]")}
=> ["192.168.1.1", "x", "xx", "xxx"]
2.5.8 :008 > data
=> "[redacted]\n[redacted]1"
2.5.8 :009 >
Just simply trying to replace an exact match with gsub.
Upvotes: 1
Views: 153
Reputation: 396
It is replacing the first match, just not the way you expect. The first pattern in your array should be '^192.168.1.1$'
if you want it to match the entire string instead of just part of it.
Upvotes: 0
Reputation: 5882
So I realized that the answer was simply adding \b
before and after the string, as follows:
replace_array.each {|s| data.gsub!(/\b#{s}\b/i, "[redacted]")}
Problem solved.
Reference: Ruby replace only exact matching string with another string
Upvotes: 1