python - 使用 SQLAlchemy 的 MySQL Regex 查询中的括号

标签 python mysql regex sqlalchemy flask-sqlalchemy

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

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

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

  • 在返回错误后某处包含 ( 而没有 ) 的搜索
  • 包含外来字符的搜索,如 Бэдц 也会返回错误<

是否有支持所有类型的搜索查询(包括特殊字符和外来字符)的解决方案?谢谢。

最佳答案

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

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

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

您需要 escape查询:

import re

query = re.escape(query)

关于python - 使用 SQLAlchemy 的 MySQL Regex 查询中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35278175/

相关文章:

python - 在 Pandas 列中应用拆分并获取结果的第二个元素,该列有时包含 None 并且有时不会拆分为超过 1 个组件

mysql - Grails 属性不能为 null 错误

mysql - INSERT IGNORE.... SELECT.... ORDER BY... LIMIT... 在 MySql 中的确切行为是什么?

java - 什么正则表达式将在收据上列出最后的价格?

Java 正则表达式 : What is the best way to filter out the keyboard characters?

python - python 上的正则表达式到单词匹配

python - 使用 BeautifulSoup 抓取亚马逊网页

python - Django 1.6 在 Django 环境中运行独立脚本 - 没有成功

个人和公司的 mySQL 联系人表

python - 在 django admin 中设置初始(默认)实例