【发布时间】:2015-02-03 13:39:22
【问题描述】:
我想用正则表达式分割字符串。
例如
when [python] or [html ] demo "css html" -[javascript] score:5
从我想要的这个字符串,以下列表,
contains = ['when', 'demo']
word_press = ["css html"]
tags = ['python', 'or', 'html', '-', 'javascript']
options = [{score:5}]
-
"[]"(括号)中的所有单词都是标签列表。 -
""之间的单词将在 word_press 列表中。 - 单词中包含
:的单词将出现在选项列表中。 - 除上述条件之外的其他条件将在包含列表中。
我试过了,
((?:or\s|-)?\[.*?\])|(".*?")|([a-z]+:\d*)|(\S+)
它工作正常,但我在 python 中使用它
>>> import re
>>> s = '''[python] or [html] how to "how to" user:2525
... [demo] how to createscore:5
... when [python] or [html] demo "css html" -[javascript] score:5'''
>>> re.findall('''((?:or\s|-)?\[.*?\])|(".*?")|([a-z]+:\d*)|(\S+)''', s)
[('[python]', '', '', ''),
('or [html]', '', '', ''),
('', '', '', 'how'),
('', '', '', 'to'),
('', '"how to"', '', ''),
('', '', 'user:2525', ''),
('[demo]', '', '', ''),
('', '', '', 'how'),
('', '', '', 'to'),
('', '', 'createscore:5', ''),
('', '', '', 'when'),
('[python]', '', '', ''),
('or [html]', '', '', ''),
('', '', '', 'demo'),
('', '"css html"', '', ''),
('-[javascript]', '', '', ''),
('', '', 'score:5', '')]
它返回列表中的元组。有没有办法获取像
这样的组group1 = ['[python]', 'or [html]', '[demo]', '[python]', 'or [html]', '-[javascript]']
...
【问题讨论】:
-
你在什么基础上尝试像上面那样拆分?
-
为什么
or是一个“标签”? -
split string according to different criteria using python,你能解释一下标准吗? -
我不会使用单个正则表达式,而是使用扫描仪。
re模块中有一个undocumentedScanner类,它使得编写这样的扫描器变得非常简单。 -
您在寻找类似this 的东西吗?如果您更清楚自己的标准会很有帮助。