Using SIMILAR TO for a regex?

两盒软妹~` 提交于 2019-12-20 07:24:10

问题


Why is the following instruction returning FALSE?

SELECT '[1-3]{5}' SIMILAR TO '22222' ;

I can't find what is wrong with that, according to the Postgres doc ...


回答1:


The operator is defined as:

string SIMILAR TO pattern 

so the first parameter is the string that you want to compare. The second parameter is the regex to compare against.

You need:

SELECT '22222' SIMILAR TO '[1-3]{5}';



回答2:


try

SELECT '22222' ~ '[1-3]{5}'

SIMILAR is not POSIX standard

The SIMILAR TO operator returns true or false depending on whether its pattern matches the given string. It is similar to LIKE, except that it interprets the pattern using the SQL standard's definition of a regular expression. SQL regular expressions are a curious cross between LIKE notation and common regular expression notation.

...

POSIX regular expressions provide a more powerful means for pattern matching than the LIKE and SIMILAR TO operators. Many Unix tools such as egrep, sed, or awk use a pattern matching language that is similar to the one described here.

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




回答3:


Your basic error has already been answered.
More importantly, don't use SIMILAR TO at all. It's completely pointless:

  • Query performance in PostgreSQL using 'similar to'
  • Difference between LIKE and ~ in Postgres

Use LIKE or regular expression match ~ or other pattern matching operators:

  • Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL

For 5 digits between 1 and 3 use the expression @Thomas provided.

If you actually want 5 identical digits between 1 and 3 like your example suggests I suggest a back reference:

SELECT '22222' ~ '([1-9])\1{4}'

Related answer with more explanation:
Deleting records with number repeating more than 5

SQL Fiddle demonstrating both.



来源:https://stackoverflow.com/questions/24656452/using-similar-to-for-a-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!