如何使用 Python REGEX 重新排序字符串(无论它是怎样的)

How to reorder a string (no matter how it is) using Python REGEX

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

str = "one two three for"

但问题是:我不知道顺序。有时它可能是 "three two for one",它可能是 "for three two one""one for two three" 或其他什么......我只需要一个正则表达式来使它成为 "one two three for" 无论如何。我想像这样的东西:

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

我什至不知道这是否有意义,或者是否有可能,哈哈,但我想你们理解我的意思。那么,你会怎么做呢? 非常感谢!

您可以执行以下操作:

import re
s = "one two three for"
r = re.compile('(\S* )(\S* )(\S* )(\S*)')
print(r.sub(r'',s))

输出:

two one three for

这似乎有点蛮力,但就是这样, 尝试一个接一个匹配 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