user3788685 user3788685 - 6 months ago 12
Ruby Question

Replace words in a string based on starting letter of each word

I have a simple Ruby script that reads in data from a file, line by line this is a sample of the data;

"SW02 CAR03 B0932 B23(B) B32(A) V1000 V0020"
"T001 T665 CAR99A B0932 S222 LA44 V1009 V0029"


I'm trying to find a way to match and replace based on the first letter of each word. eg. 'Sxxxxxx' should be replaced with the word 'SWT', 'Vxxxx' replaced with 'VAL' where 'x' is anything as shown in the example above.

File.open('test.txt').each do |line|
output = line.gsub!('V', 'VAL')
puts output


Is what I've tried so far (Which obviously doesn't work as it replaces any instance of V with VAL)

This is to automate a process to generate machine readable config files.

Answer

Use regex:

File.open('test.txt').each do |line|
  output = line.gsub!(/\bV[^\s]*/, 'VAL')
  puts output
end