首页 > 解决方案 > 如何使用 Python REGEX 重新排序字符串(不管它是怎样的)

问题描述

我是玩 REGEX 的新手,我很难过......我正在尝试使用 Python re 重新排序字符串。这是一个简单的例子,这就是我所拥有的:

str = "one two three for"

但问题是:我不知道顺序。有时可能"three two for one"是,可能是"for three two one""one for two three“或其他任何东西……无论如何,我只需要一个正则表达式即可使其成为“一二三”。我想到了这样的事情:

str = re.sub(r"some regex here", "\1 \2 \3 \4", str)  #/1 => one, /2 => two, /3 => three, /4 => for

我什至不知道这是否有意义,或者是否可能以某种方式哈哈,但我认为你们理解我。那么,你会怎么做呢?非常感谢!

标签: pythonregexcapturing-group

解决方案


这似乎有点蛮力但在这里,试图one or two or three一个接一个地匹配

代码:

import re 
sentences = ['some sentence -> one two three',
             'some other sentence ->  two three one ',
             'this is a different ->  three two one',
             'statment -> three one two',
             'this is one two statement -> two one three']
for sentence in sentences:
    print(re.sub("(one|two|three)\s+(one|two|three)\s+(one|two|three)", "one two three", sentence))

输出:

some sentence -> one two three
some other sentence ->  one two three 
this is a different ->  one two three
statment -> one two three
this is one two statement -> one two three

推荐阅读