Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python正则表达式对字符串重新排序(无论它是如何排序的)_Python_Regex_Capturing Group - Fatal编程技术网

如何使用Python正则表达式对字符串重新排序(无论它是如何排序的)

如何使用Python正则表达式对字符串重新排序(无论它是如何排序的),python,regex,capturing-group,Python,Regex,Capturing Group,我是一个玩REGEX的新手,我现在很难。。。我正在尝试使用Python re对字符串重新排序。这是一个简单的例子,我有: str = "one two three for" 但问题是:我不知道顺序。有时可能是三二对一,也可能是三二一,一对二三或者其他什么。。。我只需要一个正则表达式就可以让它变成一二三。我想到这样的事情: str = re.sub(r"some regex here", "\1 \2 \3 \4", str) #/1 => one, /2 => two, /3 =

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

str = "one two three for"
但问题是:我不知道顺序。有时可能是三二对一,也可能是三二一,一对二三或者其他什么。。。我只需要一个正则表达式就可以让它变成一二三。我想到这样的事情:

str = re.sub(r"some regex here", "\1 \2 \3 \4", 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'\2\1\3\4',s))
输出:

two one three for

这看起来有点像蛮力,但在这里, 试图一个接一个地匹配一个、两个或三个

代码:

输出:

two one three for

为什么不是四个呢?是不是必须用正则表达式?我建议你把字符串改成一二三四或一二三火!。抱歉打错了哈哈。。是的,我认为这是强制性的,不幸的是,您的正则表达式只配置了1、2、3。我正试图写一个正则表达式,它将重新排列短语,而不管单词的顺序。@EduardoFranco修复了它!
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