I'm trying to parse a text file. Occurrences of the following format are buried within continuous text (so they are never at the start of a line, for example):
"name":"Fred Flintstone","neighborhood": ...
... "name":"Barney Rubble","address":
I need to find the occurrence of "name":. name appears in other places, so only the word name with the quotes and colon should match. Then I need to print or store the text inside the first pairs of quotes to follow. I'd like to have it clean with just Barney Rubble on one line, Fred Flintstone on another.
This is what I've come up with:
File.open('textfile.txt','r') do |s|
s.each_line do |eachline|
wordmatch = eachline.match(/"name":"(.*?)(?=["])/)
puts wordmatch
end
end
but it doesn't work. The results appear like:
(lots of space)
"name":"random"
(lots of space)
"name":"Barney Rubble
It prints lots of spaces. It also is not showing all results. I don't see why.
So, apologies if it's confusing. Just to clarify. after the parser finds "name": everything inside the first, immediately following set of quotes needs to be selected/stored/printed. in the first example only Fred Flintsone should be selected, nothing else until the next "name": is encountered. Any characters and amount of space inside the quotes is legitimate.
.scan(/"name":"([^"]+)/). The captured texts are the ones you must be looking for.