首页 > 解决方案 > 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']

不要拆分引号中的内容并将文本与数字拆分。我怎样才能做到这一点?

标签: pythonregexsplit

解决方案


您可以使用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分裂为asdfand 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']

推荐阅读