Aravindhan
Aravindhan

Reputation: 3626

Ruby gsub with string manipulation

I am new to ruby and writing the expression to replace the string between the xml tags by hashing the value inside that.

I did the following to replace with the new password

puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,'New \0')
RESULT: <password>New check1</password> (EXPECTED)

My expectation is to get the result like this (Md5 checksum of the value "New check1")

<password>6aaf125b14c97b307c85fc6e681c410e</password>

I tried it in the following ways and none of them was successful (I have included the required libraries "require 'digest'").

puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,Digest::MD5.hexdigest('\0'))
puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/,Digest::MD5.hexdigest '\0')
puts "<password>check1</password>".gsub(/(?<=password\>)[^\/]+(?=\<\/password)/, "Digest::MD5.hexdigest \0")

Any help on this to achieve the expectation is very much appreciated

Upvotes: 2

Views: 144

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

This is a variant of Tilo's answer.

require 'digest'

line = "<other>stuff</other><password>check1</password><more>more</more>"

r = /(?<=<password>).+?(?=<\/password>)/

line.sub(r) { |pwd| Digest::SHA2.hexdigest(pwd) }
   #=> "<other>stuff</other><password>8a859fd2a56cc37285bc3e307ef0d9f
   #    c1d2ec054ea3c7d0ec0ff547cbfacf8dd</password><more>more</more>"

(I've displayed the returned string on two lines so make it readable without the need for horizontal scrolling.)

The regular expression reads, "match '<password>' in a positive lookbehind ((?<=...)), followed by any number of characters, lazily ('?'), followed by the string '</password>' in a positive lookahead ((?=...)).

Upvotes: 0

Tilo
Tilo

Reputation: 33732

This will work:

require 'digest'

line = "<other>stuff</other><password>check1</password><more>more</more>"

line.sub(/<password>(?<pwd>[^<]+)<\/password>/, Digest::SHA2.hexdigest(pwd))

 => "<other>stuff</other>8a859fd2a56cc37285bc3e307ef0d9fc1d2ec054ea3c7d0ec0ff547cbfacf8dd<more>more</more>"

Make sure the input is one line at a time, and you'll probably want sub, not gsub

P.S.: agree with Tom Lord's comment.. if your XML is not gargantuan in size, try to use an XML library to parse it... Ox or Nokogiri perhaps? Different libraries have different advantages.

Upvotes: 2

Related Questions