如何使用正则表达式匹配混乱的字符串

时间:2018-02-13 07:38:04

标签: regex string python-3.x

我想解决一个案例,我知道所有将是字符串输出的内容..但我不确定输出内容的顺序..

说,我的输出的预期内容是['this','output','can','be','jumbled','in','any','order'] ..

,输出可以是'this can in any order jumbled output be''this order in any can output jumbled be'

我如何在python中编写正则表达式来解决这种情况?

2 个答案:

答案 0 :(得分:0)

我担心我无法帮助Python进行处理 - 您看到的Python是我使用的正则表达式工具的建议。您的问题也不清楚您是否需要完全匹配每个预期单词的匹配,或者单个匹配单词是否也符合条件......所以这些精美的详细信息将留给感兴趣的读者作为作业; - )

这是一个让你入门的建议:

reobj = re.compile("this|output|can|be|jumbled|in|any|order", re.VERBOSE | re.DOTALL)
match = reobj.search(subject)
if match:
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()
else:
    # Match attempt failed

答案 1 :(得分:0)

实际上是可行的。例如,使用^(?=.*this)(?=.*output)(?=.*can)(?=.*be)(?=.*jumbled)(?=.*in)(?=.*any)(?=.*order)

对于每个单词,我们只是将它包含在一个正面的预测中(断言后面的内容可以从当前位置匹配),以及之前出现的任何字符。

Demo

我不是python的专家,但我确信你可以动态构建它。