How to search if whole word exists in a String in Postgres

后端 未结 3 1305
天命终不由人
天命终不由人 2021-01-25 14:46

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

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-25 15:23

    You can use a regular expression for this:

    where title ~* '(\mphone\M)|(\msamsung\M)'
    

    The above only returns values where phone or samsung are complete words. The regex modifiers\m and \M make the pattern only match for whole words.

    The regex operator ~* makes this case-insensitive. The above expression would return Samsung Phone or Google Phone but not Sam's House.

    If you want to add more words, just add them using the "or" operator |

    where title ~* '(\mphone\M)|(\msamsung\M)|(\mbhat\M)'
    

    Note that this kind of search is not going t1o be super-fast. Regular expressions are expensive they cannot make use of any index.

提交回复
热议问题