Is this the best way to use a regex and build a file?


I only have shallow knowledge of Ruby, and would like to check this is the best way to create a text file by reading items from another file through a regex:

header = "<?xml version=""1.0"" encoding=""UTF-8""?>\n<gpx>\n<trk>\n<name>RENAME ME</name>\n<trkseg>\n"
footer = "</trkseg>\n</trk>\n</gpx>\n"'test.gpx', 'w') do |file|
	file.puts header

	meat ='input.gpx')
	meat.scan(/<trkpt.+?<\/trkpt>/m) { |mtch| 
	  file.puts mtch
	file.puts footer

Thank you.

meat will be the contents of the entire file. If input.gpx is small, then it will be fine. Otherwise, you will want to process either by lines or by blocks.

But looks like the file is an XML file.

You should process it with an XML parser instead.

The ^ and $ characters mean “start” and “end” of the line, so they only match full lines consisting of one “word”. ^[a-zA-Z]S is similar, only the asterisk () means “no or any number of” the preceding character/group. The S is just an S and matches exactly one S.

I found much information from your post, thank you si much i love this forum.