0

我想提取字符串中的赋值。

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

像这样在 RUBY 中使用正则表达式

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

我试过了:

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

3 回答 3

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"]
于 2013-08-13T16:43:10.257 回答
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+/, "")}
于 2013-08-13T16:47:05.377 回答
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"]
于 2013-08-13T18:49:18.843 回答