Ruby Regexp中的逻辑运算符放置

时间:2019-02-16 05:26:09

标签: regex ruby

我有一些Ruby代码,可以在保留标点符号的同时将所有元音从字符串数组中拉出:

tabIcons

我很好奇为什么将def remove_vowels(arr) arr.map do |word| word.scan(/[\W||\w&&[^aeiou]]/).join end end arr = %w(Hello! How are you? My name is Bob; what is yours?) p remove_vowels(arr) # => ["Hll!", "Hw", "r", "y?", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"] 放在表达式的末尾,所以:

||\W

无效,而是要求以word.scan(/[\w&&[^aeiou]||\W]/).join 开头。关于Regexp的顺序是否有一些规则可以解释这一点,还是一个简单的语法错误?

1 个答案:

答案 0 :(得分:2)

||不是RegEx中的 OR ,并且在[]中,不需要 OR
您可以像这样简单地编写正则表达式:/[[\w&&[^aeiou]]\W]/。 (更新:或者只是/[^aeiou]/
另一方面,&&Class Intersection

示例:

arr
#=> ["Hello!", "How", "are", "you?", "[]||&\\", "My", "name", "is", "Bob;", "what", "is", "yours?"]
arr.map do |word| word.scan(/[[\w&&[^aeiou]]\W]/).join; end
#=> ["Hll!", "Hw", "r", "y?", "[]||&\\", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"]
arr.map do |word| word.scan(/[[\w&&[^aeiou]]|]/).join; end # | inside [] will be read literally.
#=> ["Hll", "Hw", "r", "y", "||", "My", "nm", "s", "Bb", "wht", "s", "yrs"]
arr.map do |word| word.scan(/[[\w&&[^aeiou]]||]/).join; end
#=> ["Hll", "Hw", "r", "y", "||", "My", "nm", "s", "Bb", "wht", "s", "yrs"]
## Note this one, it is OR now:
arr.map do |word| word.scan(/[\w&&[^aeiou]]|\W/).join; end
#=> ["Hll!", "Hw", "r", "y?", "[]||&\\", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"]

正如Swoveland先生在评论中正确指出的那样,/[\W||\w&&[^aeiou]]//[^aeiou]/基本相同,因为后者实际上包含了\W
另外,您可能希望添加i标志以区分大小写:

arr = %w(Hello! How are you? []||&\\ hELLO My name is Bob; what is yours?)
arr.map do |word| word.scan(/[\W||\w&&[^aeiou]]/).join; end
#=> ["Hll!", "Hw", "r", "y?", "[]||&\\", "hELLO", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"]
arr.map do |word| word.scan(/[^aeiou]/).join; end
#=> ["Hll!", "Hw", "r", "y?", "[]||&\\", "hELLO", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"]
arr.map do |word| word.scan(/[^aeiou]/i).join; end
#=> ["Hll!", "Hw", "r", "y?", "[]||&\\", "hLL", "My", "nm", "s", "Bb;", "wht", "s", "yrs?"]