From: Mike Stok Date: 2006-09-15T09:15:43+09:00 Subject: Re: Newbie regexp question On 14-Sep-06, at 7:37 PM, James Calivar wrote: > Hello, > > I'm trying to split a formatted text file into four separate columns. > The data is comprised of lines of text that are bundled into four > distinct columns, corresponding to a "Required versus Optional" > variable, a requirement number, a requirement classification > (R1=Rev 1, > F=Future, I=Internal), and a textual description of the requirement. > > My raw data looks like this in the input text file: > > R [01] R1 The system shall support "emergency call processing" > R [02] R1 The system shall support "local call processing" > R [08] F The system shall provide a command-line user interface > R [723] F The system shall provide 6 10/100/1000 Ethernet interfaces > R [11] F The system shall support VoIP networks > R [398] R1 The system shall contain 2 control boards > O [327] I The system should support hotswapping of all internal boards > R [19] I The system shall be able to detect transmission errors > R [631] F The system shall continue processing data as long as a > call is > active. > > I've set up a loop to process each line in the input file, and what > I'd > like to get is four separate variables containing on a line-by-line > basis the data corresponding to the four distinct columns. The > problem > is my regexp experience is next to nothing, and I can't figure out how > to extract the data I want since my fourth column contains whitespace > (I'd have used that as my column separator otherwise). > > Here's my loop: > > File.open(textfile, "r") do |input_file| > while line = input_file.gets > output_file << line > end > end > > What can I replace the simple copy statement (output_file << line) > with > in order to get what I want? > > Thanks in advance, I hope this question makes some sense. You have a number of options - if your data is tab delimited (i.e. the first "two" coluumns are really one): s = 'R [01] R1 The system shall support "emergency call processing"' p s.split(/\t/) => ["R [01]", "R1", "The system shall support \"emergency call processing\""] or you can just split on whitespace and specify a limit on the number of fields: s = 'R [01] R1 The system shall support "emergency call processing"' p s.split(/\s+/, 4) => ["R", "[01]", "R1", "The system shall support \"emergency call processing\""] Or you can use a regex (ick ;-) Hope this helps, Mike -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.