From: 7stud -- Date: 2009-08-15T16:03:07+09:00 Subject: Re: regexp issue on parsing from file Alpha Blue wrote: > Correction > > counter = 1 > name_re = /(.*)\[(.*)\{/ > File.open("census.lua", "r") do |infile| > while (line = infile.gets) > if (line =~ name_re) > s_line = line.strip > c_line = s_line.size > right = c_line - 7 > puts "#{counter}: #{s_line.slice!(2..right)}" > counter = counter + 1 > end > end > end Ben's regex is better, and once you've done the matching, if your regex has a group around the desired information, you can retrieve the desired information--there is no need to slice and dice the string to extract the information: count = 1 IO.foreach("data.txt") do |line| if md = /^\["(\w+?)"\]/.match(line) puts "#{count}: #{md[1]}" count += 1 end end --output:-- 1: Name 2: NameTwo The term: /^\["(\w+)"\]/.match(line) returns a MatchData object if there is a match. Otherwise, it returns nil. That result is assigned to the variable md. A MatchData object will evaluate to true. So if a MatchData object is returned, i.e. there is a match, the if condition will evaluate to true, and the body of the if statement will execute. Inside the if statement, you can ask the MatchData object for the match for the group in your regex. md[0] is the whole match, md[1] is the match for group 1, md[2], is the match for group 2, etc. The regexp says to look for the start of the string(^), then an opening bracket, then a double quote mark, then any character [a-zA-Z0-9] one or more times(+), then a quote mark, then a closing bracket. -- Posted via http://www.ruby-forum.com/.