开发者

Finding a regex match from an array of regexes

开发者 https://www.devze.com 2023-02-25 19:55 出处:网络
def match_line regex @line.match(regex) if !regex.is_a?(Array) regex.each {|rgx| results = @line.match(rgx)
def match_line regex
    @line.match(regex) if !regex.is_a?(Array)
    regex.each {|rgx| 
        results = @line.match(rgx) 
        return results if !results.nil? 
    }
    return nil
end

This looks like something that could be done in a one line idiomatic way, and I'm just not 开发者_StackOverflow中文版seeing how.


[*regex].map{ |re| @line.match re }.compact.first

or

Array(regex).map{ |re| @line.match re }.compact.first


 [*regex].find{|r| @line.match(r)}
 return $~ #will return the last MatchedData returned, otherwise nil.

$~ will return the last MatchedData returned, otherwise nil.


def match_line regex
  [*regex].each { |r| return r if (r = @line.match r) }
end


It is a preferred, established practice to pass arguments in this case like

match_line(regex1, regex2, ...)

or

match_line(*array_of_regexes)

rather than

match_line([regex1, regex2, ...])

or

match_lines(array_of_regexes)

so your conditioning regarding array-ness is unnecessary.

def match_line *regex
  regex.detect{|r| @line =~ r}
  Regexp.last_match
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号