简体   繁体   English

带SQLAlchemy的MySQL Regex查询中的括号

[英]Parenthesis in MySQL Regex queries with SQLAlchemy

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. 谢谢。

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)

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

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