Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to check if all words in a string selection are present in another string. There will be an arbitrary number of words. This is not an OR. All words MUST be present in the matcher. Order does not matter. For example, when selection is "John Zeni", it must match " John Paul Zeni" because both "John" and "Zeni" are in the matcher. If selection was just "John", then it should match, but since there are multiple words, all words must match. Regex solution is required.

This is what I tried:

selection = "John Zeni"
pattern = selection.split(" ").join("|")
# => "John|Zeni"
/#{Regexp.quote(pattern)}/
# => /John|Zeni/ 
" John Paul Zeni".match(/#{Regexp.quote(pattern)}/)
# => nil 

Why doesn't it match? The problem is with Regexp.quote I think. It is important that both words match in the matcher. This also should not match:

" John Paul Zeni" =~ /(John|Zach)/ 
# => 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
239 views
Welcome To Ask or Share your Answers For Others

1 Answer

("John Zeni".split - "John Paul Zeni".split).empty?
  #=> true

If str may contain punctuation we should remove those characters before splitting.

("John Zeni Lola".split - "John Lola Paul, Zeni.".gsub(/[[:punct:]]/,'').split).empty?
  #=> true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...