Django的。 PostgreSQL的。 regexp_split_to_table不工作 [英] Django. PostgreSQL. regexp_split_to_table not working

查看:794
本文介绍了Django的。 PostgreSQL的。 regexp_split_to_table不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用查询来表示我的表字段。

 从mytable limit 20选择regexp_split_to_table(mytable.field_name,E'\\\s +') 

当我从psql shell执行它时,但是当我执行这个工作:

  from django.db import connection cursor = connection.cursor()
cursor.execute(SELECT regexp_split_to_table(mytable.field_name,E'\ \s +')
FROM mytable LIMIT 20)
cursor.fetchall()

...无法返回令牌。我做错了什么?

解决方案

反斜杠被Django视为元字符,并在双引号内解释。
因此,在字符串到达​​PostgreSQL服务器之前,一层 E'\\s +')将被剥离,这将看到 E'\s +')。转义字符串将导致's +',这又会使 regexp_split_to_table()将您的字符串分割成任意数量的 s 而不是非打印空间,正则表达式中的字符类简写 \s p>

将字符串中的反斜杠加倍以获得所需的内容: E'\\\\\s +')

 SELECT regexp_split_to_table(field_name,E'\\\\\s +')FROM mytable LIMIT 20 

另外,为避免出现问题,反斜杠的特殊含义 \\ ,您可以使用 [[:space:]] 表示相同的字符类:


$ b $ b


手册中的模式匹配


I am trying to tokenize my table fields with a query.

SELECT regexp_split_to_table(mytable.field_name, E'\\s+') from mytable limit 20;

This works when I execute it from psql shell but when I do:

from django.db import connection cursor=connection.cursor() 
cursor.execute("SELECT regexp_split_to_table(mytable.field_name,E'\\s+')
                FROM mytable LIMIT 20") 
cursor.fetchall()

... it fails to return tokens. What am I doing wrong?

解决方案

The backslash is treated as meta-character by Django and is interpreted inside double quotes. So one layer of E'\\s+') gets stripped before the string arrives at the PostgreSQL server, which will see E'\s+'). The escape string will result in 's+' which in turn will make regexp_split_to_table() split your strings at any number of s instead of non-printing space, which the character class shorthand \s stands for in regular expressions.

Double your backslashes in the string to get what you intended: E'\\\\s+'):

"SELECT regexp_split_to_table(field_name, E'\\\\s+') FROM mytable LIMIT 20"

As an alternative, to avoid problems with the special meaning of the backslash \, you can use [[:space:]] to denote the same character class:

"SELECT regexp_split_to_table(field_name, '[[:space:]]+') FROM mytable LIMIT 20"

Details in the chapter "Pattern Matching" in the manual.

这篇关于Django的。 PostgreSQL的。 regexp_split_to_table不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆