1

Say I have the following array of addresses

array = ["1 New Street, Filton Grove, Bristol BD7 0AA", "2 New Street, Filton Grove, Bristol BD7 0AA", "3 New Street, Filton Grove, Bristol BD7 0AA"]

I would like to check that each item in the array contains the words Filton Grove Bristol, but as there are commas within the address is is throwing me slightly.

How do I ignore the commas and check that each word exists in each iteration of the array

So far I have this

regexp = /^Filton Grove Bristol/i
array.all? { |a| regex =~ a }

But this fails.

1
  • Do they ALL contain a comma? Commented Apr 14, 2015 at 8:57

5 Answers 5

2

You could check for words separately.

regexp_checks = [/Filton/i, /Grove/i, /Bristol/i]
array.all? { |a| regexp_checks.all?{|rgx| a =~ rgx} }
Sign up to request clarification or add additional context in comments.

1 Comment

This is best if you dont want the order of words :)
2

If the three words must be in the specific sequence, try this:

regexp = /Filton[,\s]+Grove[,\s]+Bristol/i

Comments

2

You could also check in this way..

regexp_checks = [/Filton.*?Grove.*?Bristol/i]
array.all? { |a| regexp_checks.all?{|rgx| a =~ rgx} }

Note: Use this only if you want to maintain the order of words appearing. And if order is important and no other words should be allowed in between.. you can use
regexp_checks = [/Filton\W+Grove\W+Bristol/i]

1 Comment

Thank You, In my case the order of the words would be quite useful
2

Try the following regex

regexp = /Filton Grove,?\s*Bristol/i

You do not need the ^ in your regex.

Comments

1

For all possible use cases

regexp = /Filton[\s,\s]*Grove[\s,\s]*Bristol/i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.