使用正则表达式提取 Ruby 中的子字符串

Extract a substring in Ruby using a regular expression

如何从字符串中提取子字符串作为 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 和字段值, 过滤后,它看起来像

字段:名称 => 6

问题不明确,但假设如下,
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"]

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

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

除字段名称外,仍然提供相同的输出。

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

希望这对您有所帮助。

这是一个将分别检索字段名称和值的正则表达式:

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