0

A survey software I'm using allows to exclude sites on which the survey should be shown using Ruby based Regex (they recommend testing strings on rubular.com). I don't want to show the survey to clients that are close to finishing transaction, so excluding 3 phrases makes more sense to me than including all the rest.

How would I have to approach writing a ruby regex string that includes everything except phrases cart, order and login within the URL?

Matt
  • 75
  • 3
  • 11
  • 1
    regex's aren't very good at matches like "everything that doesn't contain a particular word". But this question might be useful http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – Max Williams May 19 '14 at 11:45

1 Answers1

2

The following ruby code rejects all strings in the array containing cart, order or login.

urls.reject { |url| url[/(cart|order|login)/] }

A raw regular expression which excludes words will use negative look-arounds:

^((?!login|order|cart).)*$

See rubular.

For more information, see @Max's suggested reading at Regular expression to match a line that doesn't contain a word?

Community
  • 1
  • 1
Uri Agassi
  • 35,245
  • 12
  • 68
  • 90
  • Rubular notified me of escaping forward slashes, which I added to your string, but then it still didnt match 1 of 4 testing URLs that didnt have any of the aforementioned phrases. – Matt May 19 '14 at 11:46
  • The forward slashes are the ruby syntax for regular expressions, much like quotes are for strings. Also, using `reject` _throws away_ any matching URLs, and _keeps_ only those which do not match. – Uri Agassi May 19 '14 at 11:51
  • Matt, please could you share the failing testing URL? – Zlatin Zlatev May 19 '14 at 12:07
  • Sure, I'm still reading various materials regarding negative lookahead, but can't seem to write such a string. [Here is Uri's string with my testing URL's.](http://rubular.com/r/WTU5EGJm4H) – Matt May 19 '14 at 12:12
  • 1
    @Matt - we are having some misunderstanding - what I posted is _ruby code_, not a standalone regular expression. The raw regular expression is `(cart|order|login)`, which selects all the URLs which _contain_ cart,order or login. – Uri Agassi May 19 '14 at 12:15
  • That would explain a lot :) But still, I knew how to select phrases with OR statement, but can't figure out how to **exclude** them instead of including them. Is this possible at all? – Matt May 19 '14 at 12:19