Ruby中不区分大小写的正则表达式匹配

您所在的位置:网站首页 grep正则匹配 Ruby中不区分大小写的正则表达式匹配

Ruby中不区分大小写的正则表达式匹配

2023-02-22 11:40| 来源: 网络整理| 查看: 265

我有一个阵列,上面有电力别动队颜色列表, rangers = ["red", "blue", "yellow", "pink", "black"]

我想验证给定的参数是否与电力别动队颜色匹配,但问题是该参数可能以不同的情况出现(大写,小写,混合)。

例:

def validate_rangers(color) rangers = ["red", "blue", "yellow", "pink", "black"] rangers.grep(color).any? end validates_rangers("red") #=> true

validates_rangers("Red") #=> false. Needs to be true.

如何使用不区分大小写的grep?

1> Federico Pia..:

您可以使用不敏感标志:

rangers.grep(/#{color}/i).any?

由于该标志使正则表达式不敏感,因此它将匹配 red

工作演示

def validate_rangers(color) rangers = ["red", "blue", "yellow", "pink", "black"] rangers.grep(/#{color}/i).any? end

2> tadman..:

解决此问题的更惯用的Ruby方法如下所示:

# Define a constant that defines the colors once and once only. RANGERS = ["red", "blue", "yellow", "pink", "black"] def validates_rangers(color) # Check against an arbitrary object that may or may not be a string, # and downcase it to match better. RANGERS.include?(color.to_s.downcase) end

如果您经常这样做,则可能要使用a Set优化性能:

RANGERS = Set.new(["red", "blue", "yellow", "pink", "black"])

不需要任何代码更改,但是查找要快得多。

如果您打算使用正则表达式:

# Construct a case-insensitive regular expression that anchors to the # beginning and end of the string \A...\z RANGERS = Regexp.new( '\A(?:%s)\z' % Regexp.union("red", "blue", "yellow", "pink", "black"), Regexp::IGNORECASE ) def validates_rangers(color) # Double negation returns true/false instead of MatchData !!RANGERS.match(color.to_s.downcase) end validates_rangers("Red") # => true validates_rangers("dred") # => false


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3