2016-05-16 111 views
-2

如何从字符串中提取子字符串作为Ruby中的字段名称?使用正则表达式在Ruby中提取子字符串

输出示例:

A-field:name.23.134 => 6 

ruby { 
     code => " 

      if key =~ /^A-field:[A-Za-z]+/ then 
        #how to get the match pattern ?and the field value ?      

       end 


} 

如何获得匹配图案作为字段ANME和字段值, 过滤后,它的将是貌似

A-字段:名称=> 6

回答

0

这里有一个正则表达式,将检索字段名和单独的值:

text = "A-field:name.23.134 => 6" 
matches = text.match(/([^:]+:[^=\.\s]+)(\.\d+)*\s*=>\s*(.+)/) 
puts "Field: #{matches[1]}" 
puts "Value: #{matches[3]}" 
puts "#{matches[1]} => #{matches[3]}" 

的这个输出是:

Field: A-field:name 
Value: 6 
A-field:name => 6 
1

问题不明确,但假设如下,
1.字符串形式为(field1).numbers_to_ignore => number_to_capture

你试试这个。

string = "A-field:name.23.134 => 6" 
matchdata = string.match /(?<field1>[^.]*).*(?<field2>=>.*)/ 
matchData[1] 
>> "A-field:name" # same result as matchData["field1"] 
matchData[2] 
>> "=> 6" # same result as matchData["field2"] 

或以简单的形式,你可以使用正则表达式这样

/([^.]*).*(=>.*)/ 

这仍然给除了字段名称相同的输出。

第一个圆括号在'=>'字符之前捕获除点之外的所有字符。然后,第二个括号捕获以'=>'开头的所有字符。

希望这会有所帮助。