使用SQLAlchemy进行MySQL Regex查询中的括号

时间:2022-02-02 23:34:45

I have a python application which searches a database using SQLAlchemy like so:

我有一个python应用程序,它使用SQLAlchemy搜索数据库,如下所示:

query = raw_input('Search: ')
db.session.query(Posts).filter(Posts.name.op('REGEXP')(r'[[:<:]]{}'.format(query))).all()

This works fine with my MySQL database with most characters however I have found some searches do not work.

这适用于我的MySQL数据库与大多数字符,但我发现一些搜索不起作用。

  • Searches that include ( without a ) following it somewhere after return an error
  • 在返回错误后包含(不带)跟踪它的搜索
  • Searches that contain foreign characters like Б, э, д or ц also returns an error
  • 包含Б,э,д或ц等外来字符的搜索也会返回错误

Is there a solution to support ALL kinds of search queries including special and foreign characters? Thanks.

是否有支持各种搜索查询的解决方案,包括特殊字符和外来字符?谢谢。

1 个解决方案

#1


0  

Searches that include ( without a ) following it somewhere after return an error

在返回错误后包含(不带)跟踪它的搜索

This is happening since ( and ) have special meaning in regular expressions. The expression would not be valid, if, for example, there is an opening parenthesis without a closing one:

这是因为(和)在正则表达式中具有特殊含义。例如,如果有一个没有结束符的左括号,则该表达式无效:

>>> re.compile(r"test (")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  ...
error: unbalanced parenthesis

You need to escape the query:

您需要转义查询:

import re

query = re.escape(query)

#1


0  

Searches that include ( without a ) following it somewhere after return an error

在返回错误后包含(不带)跟踪它的搜索

This is happening since ( and ) have special meaning in regular expressions. The expression would not be valid, if, for example, there is an opening parenthesis without a closing one:

这是因为(和)在正则表达式中具有特殊含义。例如,如果有一个没有结束符的左括号,则该表达式无效:

>>> re.compile(r"test (")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  ...
error: unbalanced parenthesis

You need to escape the query:

您需要转义查询:

import re

query = re.escape(query)