Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby RegexpError:带不匹配括号的结束模式_Ruby_Regex - Fatal编程技术网

Ruby RegexpError:带不匹配括号的结束模式

Ruby RegexpError:带不匹配括号的结束模式,ruby,regex,Ruby,Regex,我有 作为字符串的品牌列表 品牌=‘劳伦斯·比尔·劳伦斯·比尔·迪迪特·宾森·比奇斯陷阱Biyang Black Arts’相当大 如果我的字符串包含其中一个,我希望它找到什么 my_str = ' txt txt OBL txt' my_str[(/#{brands}/)] 但我得到了RegexpError:带有不匹配括号的结束模式 我做错了什么?如果要“查找我的字符串是否包含其中一个”,则不需要正则表达式: brands = %w|BAR FOO| my_str = ' txt txt

我有 作为字符串的品牌列表 品牌=‘劳伦斯·比尔·劳伦斯·比尔·迪迪特·宾森·比奇斯陷阱Biyang Black Arts’相当大

如果我的字符串包含其中一个,我希望它找到什么

my_str = ' txt txt OBL txt'

my_str[(/#{brands}/)]
但我得到了RegexpError:带有不匹配括号的结束模式


我做错了什么?

如果要“查找我的字符串是否包含其中一个”,则不需要正则表达式:

brands = %w|BAR FOO|
my_str = ' txt txt BAR txt'
brands.any? { |brand| my_str.include? brand }
#⇒ true
brands.detect { |brand| my_str.include? brand }
#⇒ "BAR"
不幸的是,这将匹配类似字符串的文本中的条。为了避免这种情况:

my_str =~ Regexp.union brand.map(&:Regexp.escape).map { |e| "\b#{e}\b" }
事实上,由于Regexp.union本身会转义字符串,因此应将其编写为:

my_str =~ Regexp.union brand.map { |e| "\b#{e}\b" }
对于那些懒得理解简单英语的人:

my_str.scan Regexp.union brand.map { |e| "\b#{e}\b" }

逃逸品牌内容。正如@WiktorStribiżew所说:my_str[/{Regexp.Escape brands}/]也注意到括号是多余的。如果匹配,我想返回品牌名称,不仅是trueit有效,而且如果我有my_str='maraca Meinl MSM4',并使用brands.detect{brand{brand | my_str include?brand}它给了我MSM,除了Mein MeNL和MSM——我的品牌。你介意阅读答案而不是盲目复制粘贴的片段吗?考虑使用语义正确的ReGExpUnEng+而不是加入'`'。@ MuasasbWa:谢谢你的提示。我更改了我的答案。而且我会在/\W+/而不是单个/\W/上拆分,以避免e的结果为空。G“你看,逗号。”
pattern = Regexp::union(brands.strip.split(/\W+/))
# => "/Lawrence|Bill|OBL|Billdidit|Binson|Bitchstraps|Biyang|Black|Arts/"

my_str.match(pattern)
# => #<MatchData "OBL">

my_str.scan(pattern)
# => ["OBL"]