I have a table with a column field
that has values like Samsung Phone.
My question is how can I get this row if I search for a string \"Samsung\" or \"phone
The following solutions are tested in PostgreSQL 9.6.
You may use the \y word boundary and a grouping construct with alternation operator separating all possible alternatives:
where title ~* '\y(?:Samsung|phone)\y'
Or, case insensitively:
where title ~* '\y(?:Samsung|phone)\y'
See the PostgreSQL demo.
Note that \y
is not the right approach when the first or last char are not word chars. E.g. you want to search for #samsung
or phone#
. Then, consider using unambiguous word boundaries:
where title ~* '(?
Here, the (? negative lookbehind fails the match if there is a non-alnum and no
_
char immediately to the left of the current position, and the (?!\w)
is a negative lookahead fails the match if there is a non-alnum and no _
char immediately to the right of the current position. Equivalent for testing if there is a match in where
clause is:
where title ~* '(\W|^)(?:#samsung|phone#)(\W|$)'
See another PostgreSQL demo online:
CREATE TABLE mmytable
(title character varying)
;
INSERT INTO mmytable
(title)
VALUES
('#Samsung Co.'),
('They have a phone#'),
('Uncle Sam phoned him')
;
select * from mmytable where title ~* '(?
Also, consider whitespace boundaries when you need to match only in between whitespace characters or start/end of string:
where title ~* '(?