Reputation: 2787
I'm wondering how to check for regular expressions in Ruby. I would like to check files where lines are in this format:
id: 123456 synset: word1,word2,etc
The number of digits of the integer doesn't matter. How many words are in synset
doesn't matter either.
Am I supposed to use Regexp?
Upvotes: 0
Views: 185
Reputation: 9497
./file1.rb:
id: 123456 synset: word1,word2
id: 123456 synset: word1,word2
a;sdlkfjasdlkfj
id: 123456 synset: word1,word2
./file2.rb
file = File.new('./file1.rb','r+')
p file.grep(/^id: \d+ synset: (\w+,?)+$/)
#[
# id: 123456 synset: word1,word2,
# id: 123456 synset: word1,word2,
# id: 123456 synset: word1,word2"
#]
Uses Enumerable#grep to return an array of only the lines which match the regex.
Upvotes: 0
Reputation: 6076
Regex would be handy here:
str = 'id: 123456 synset: word1,word2,etc'
m = str.match(/\Aid: (\d+) synset: (.+)\z/)
id, synset = m.captures
id
=> "123456"
synset
=> "word1,word2,etc"
Or you could split the string into an array:
arr = str.split
_, id, _, synset = arr
id
=> "123456"
synset
=> "word1,word2,etc"
Upvotes: 1