regex - Use ARGV[] argument vector to pass a regular expression in Ruby -
i trying use gsub
or sub
on regex passed through terminal argv[]
.
query in terminal: $ruby script.rb input.json "\[\{\"src\"\:\"
input file first 2 lines:
[{ "src":"http://something.com", "label":"foo.jpg","name":"foo", "srcname":"foo.jpg" }] [{ "src":"http://something123.com", "label":"foo123.jpg", "name":"foo123", "srcname":"foo123.jpg" }]
script.rb:
dir = file.dirname(argv[0]) output = file.new(dir + "/output_" + time.now.strftime("%h_%m_%s") + ".json", "w") open(argv[0]).each |x| x = x.sub(argv[1]),'') output.puts(x) if !x.nil? end output.close
this basic stuff really, not quite sure on how this. tried:
regexp.escape
pattern:[{"src":"
.- escaping characters , not escaping.
- wrapping pattern between quotes , not wrapping.
meditate on this:
i wrote little script containing:
puts argv[0].class puts argv[1].class
and saved disk, ran using:
ruby ~/desktop/tests/test.rb foo /abc/
which returned:
string string
the documentation says:
the pattern typically regexp; if given string, regular expression metacharacters contains interpreted literally, e.g. '\d' match backlash followed ‘d’, instead of digit.
that means regular expression, though appears regex, isn't, it's string because argv
can return strings because command-line can contain strings.
when pass string sub
, ruby recognizes it's not regular expression, treats literal string. here's difference in action:
'foo'.sub('/o/', '') # => "foo" 'foo'.sub(/o/, '') # => "fo"
the first can't find "/o/"
in "foo"
nothing changes. can find /o/
though , returns result after replacing 2 "o".
another way of looking @ is:
'foo'.match('/o/') # => nil 'foo'.match(/o/) # => #<matchdata "o">
where match
finds nothing string can find hit /o/
.
and leads what's happening in code. because sub
being passed string, it's trying literal match regex, , won't able find it. need change code to:
sub(regexp.new(argv[1]), '')
but that's not has change. regexp.new(...)
convert what's passed in regular expression, if you're passing in '/o/'
resulting regular expression be:
regexp.new('/o/') # => /\/o\//
which not want:
'foo'.match(/\/o\//) # => nil
instead want:
regexp.new('o') # => /o/ 'foo'.match(/o/) # => #<matchdata "o">
so, besides changing code, you'll need make sure pass in valid expression, minus leading , trailing /
.
Comments
Post a Comment