Re: Regular Expressions

From: Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
To: "Mark Williams" <markwillimas(at)gmail(dot)com>
Cc: <pgsql-sql(at)lists(dot)postgresql(dot)org>
Subject: Re: Regular Expressions
Date: 2018-11-05 17:51:19
Message-ID: 878t272zlw.fsf@news-spur.riddles.org.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

>>>>> "Mark" == Mark Williams <markwillimas(at)gmail(dot)com> writes:

Mark> I can't figure out how to search myfield for all instances which
Mark> contain "text1" AND "text2".

I should start by pointing out that (as mentioned by other people) using
regexps is not necessarily the best way to do this, especially not when
dealing with actual words which is what FTS exists for.

But a solution does exist (at least in pg and other regexp engines that
support lookahead assertions):

myfield ~* '^(?=.*\mtext1\M)(?=.*\mtext2\M)'

What this says is: match at the start of the string if (and only if)
both the lookahead assertions succeed; since neither assertion advances
the match, they will find the two specified words regardless of the
order in which they appear. (The trick of using | to search for both
possible orders works for 2 words, but gets unwieldy very quickly with
more; with the assertion method you can handle any number of words.)

--
Andrew (irc:RhodiumToad)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Campbell, Lance 2018-11-09 16:46:33 Help with a not match
Previous Message David G. Johnston 2018-11-05 15:08:45 Re: multiple roles for a user ?