简体   繁体   English

Rails SQL:如何搜索表中的列而忽略所有特殊字符

[英]Rails SQL: How to search on a column in a table ignoring all special characters

I am searching for matching values in MyTable.我正在 MyTable 中搜索匹配的值。

name to search for -> This-is-a (test/with/time)
The name from DB table -> "this-is-a-test-with/time"

If I can get both the column value and the search value to match on something like this -> "thisisatestwithtime" which ignores all special characters and spaces.如果我可以让列值和搜索值都匹配这样的东西 - > "thisisatestwithtime" ,它会忽略所有特殊字符和空格。

value = This-is-a (test/with/time)
MyTable.where("upper(name) = upper(?)",value.to_s.scan(/[0-9a-z]/i).join("")).first

This converts the value to a form where all special characters are removed but how can I run the same on the value is in the table?这会将值转换为删除所有特殊字符的形式,但如何对表中的值运行相同的格式?

You can use a regular expression search.您可以使用正则表达式搜索。

select * from "table" where "name" ~ 'this' and name ~ 'is' and name ~ 'a' 
and name ~ 'test' and name ~ 'with' and name ~ 'time';

If you want to search whole words only (for example find -a- instead of cat )如果您只想搜索整个单词(例如 find -a-而不是cat

name ~ '\ma\M'

For case insensitive, use如果不区分大小写,请使用

name ~* 'a'

https://www.postgresql.org/docs/9.6/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP https://www.postgresql.org/docs/9.6/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP

You can also use replace to match the whole values您还可以使用replace来匹配整个值

select * from table where regex_replace(name, '\W', '') = :name

Table.where("regex_replace(name, '\W', '') = :name", name: 'thisisatestwithtime')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM