ruby - 检查字符串是否包含 Ruby 数组中的任何子字符串

标签 ruby regex substring

我正在使用 Tmail 库,对于电子邮件中的每个附件,当我执行 attachment.content_type 时,有时我不仅会得到内容类型,还会得到名称。示例:

image/jpeg; name=example3.jpg

image/jpeg; name=example.jpg

image/jpeg; name=photo.JPG

image/png

我有一组像这样的有效内容类型:

VALID_CONTENT_TYPES = ['image/jpeg']

我希望能够检查内容类型是否包含在任何有效的内容类型数组元素中。

在 Ruby 中这样做的最佳方式是什么?

最佳答案

有多种方法可以实现这一点。您可以检查每个字符串,直到使用 Enumerable#any? 找到匹配项为止:

str = "alo eh tu"
['alo','hola','test'].any? { |word| str.include?(word) }

尽管将字符串数组转换为正则表达式可能会更快:

words = ['alo','hola','test']
r = /#{words.join("|")}/ # assuming there are no special chars
r === "alo eh tu"

关于ruby - 检查字符串是否包含 Ruby 数组中的任何子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215590/

相关文章:

regex - Powershell 正则表达式 : Replace only multiple spaces with tabs

c++ - 集合中元素的子串

ruby - Digest::SHA2.hexdigest 从相同的参数生成两个完全不同的值

ruby - 在 headless (headless) EC2 机器上运行 Selenium ?

ruby - Sublime Text 是否支持 Ruby API(自动完成)?

regex - ColdFusion 中格式错误的正则表达式

arrays - 正则表达式匹配给定数据中的最后一个值

regex - (win/linux) 具有良好正则表达式支持的文本编辑器

javascript - 使用子字符串在javascript中剪切并重新构造字符串

c - 使用 fork() 的单词频率