python - Python 正则表达式拆分
问题描述
我有一个可以过滤某些数据库列的字段。但是我无法根据需要拆分搜索字符串:
我有这个例子:
import re
search = ' test "no splits234" this-splits this_not_splits asdf123 '
re.split(r'[\s]*[\W][\s]*', search.strip())
['test', 'no', 'splits234', 'this', 'splits', 'this_not_splits', 'asdf123']
需要这个输出:
['test', 'no splits234', 'this', 'splits', 'this_not_splits', 'asdf', '123']
不要拆分引号中的内容并将文本与数字拆分。我怎样才能做到这一点?
解决方案
您可以使用findall
此正则表达式:
>>> search = ' test "no splits234" this-splits this_not_splits asdf123 '
>>> print re.findall(r'"[^"\\]*(?:\\.[^"\\]*)*"|[^\s-]+', search)
['test', '"no splits234"', 'this', 'splits', 'this_not_splits', 'asdf123']
正则表达式详细信息:
- 表达式
"[^"\\]*(?:\\.[^"\\]*)*"
匹配由双引号括起来的字符串,忽略所有转义引号。 - 如果没有带引号的字符串,那么我们只需使用 1+ 非空格、非连字符匹配
[^\s-]+
如果您想避免捕获引号,请使用:
>>> print re.findall(r'(?<=")[^"\\]*(?:\\.[^"\\]*)*(?=")|[^\s"-]+', search)
['test', 'no splits234', 'this', 'splits', 'this_not_splits', 'asdf123']
更新:
OP 还显示了最后asdf123
分裂为asdf
and 123
。对于以下正则表达式可能有效:
>>> print re.findall(r'(?<=")[^"\\]*(?:\\.[^"\\]*)*(?=")|\b[a-zA-Z]+(?=\d)|(?<=[a-zA-Z])\d+|[^\s"-]+', search)
['test', 'no splits234', 'this', 'splits', 'this_not_splits', 'asdf', '123']
推荐阅读
- python-3.x - 我正在尝试找到将字符添加到字符串的所有可能组合
- sql - 如何保持运行总列但按条件停止
- javascript - 在客户端的 XMLHttpRequest 之后,如何在服务器端获取 FormData 值?
- environment-modules - 环境模块的加载/卸载是否可交换/关联?
- java - 在 Java 中将多个对象添加到列表时遇到问题
- prometheus - 当天 Prometheus 指标的总和
- node.js - 如何在 mongo DB 中设置或更新值
- firebase - 向 Flutter 应用的新用户发送欢迎电子邮件
- javascript - 通过 ajax 调用减少图像数量时,光滑滑块上的图像幻灯片无法正确显示
- c# - 我们可以在 MVC的文件中传递会话信息吗?