简体   繁体   English

Ruby检查正则表达式

[英]Ruby check regular expressions

New to ruby here, 红宝石在这里是新手,

I'm wondering how to check for regular expressions in Ruby. 我想知道如何在Ruby中检查正则表达式。 Read a lot of the documentations but it was quite confusing. 阅读了很多文档,但这很令人困惑。

I need to check files with lines 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 neither. 整数的位数无关紧要,同义词集中有多少个单词也无关紧要。

Am I suppose to use Regexp ? 我应该使用Regexp吗? Can someone give me an example? 有人可以给我一个例子吗?

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" 

./file1.rb: ./file1.rb:

id: 123456 synset: word1,word2
id: 123456 synset: word1,word2
a;sdlkfjasdlkfj
id: 123456 synset: word1,word2

./file2.rb ./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. 使用Enumerable#grep返回仅包含与正则表达式匹配的行的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM