如何从文本中提取这些内容

时间:2013-08-13 16:37:20

标签: ruby-on-rails ruby

我想在字符串中提取指定的值。

"a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"

喜欢这个IN RUBY使用REGEX

["a=b","c=d","e=f", "g=h"]

我试过了:

'a= b sadfsf c= d'.scan(/\w=(\w+)/) 

3 个答案:

答案 0 :(得分:4)

"a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
.scan(/(\w+)\s*=\s*(\w+)/).map{|kv| kv.join("=")}

# => ["a=b", "c=d", "e=f", "g=h"]

答案 1 :(得分:1)

它将字符串与正则表达式分开,然后将其存储在数组

然后删除=符号

周围的空白区域
str = "a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
results = str.scan(/[\w]+\s*\=\s*[\w]+/)
results.each { |x| x.gsub!(/\s+/, "")}

答案 2 :(得分:0)

s = "a=b  xxxxxx c = d xxxxxxxxx  e= f    g =h"
s.scan(/[[:alpha:]][[:blank:]]*=[[:blank:]]*[[:alpha:]]/).map{|e| e.delete(" ")}
# => ["a=b", "c=d", "e=f", "g=h"]