python - 如何使用 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
我什至不知道这是否有意义,或者是否可能以某种方式哈哈,但我认为你们理解我。那么,你会怎么做呢?非常感谢!
解决方案
这似乎有点蛮力但在这里,试图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
推荐阅读
- reactjs - React Material-Table 如何传递 rowData 参数?
- javascript - 麦克风访问 Microsoft Edge
- arangodb - 如何在 ArangoDB 中的对象数组中过滤和排序对象数组
- c# - 如何在 ListView.SelectionChanged 上获取 SelectedItem 的父项
- c++ - 将 doxygen 转换为乳胶到 pdf 的问题
- android - 如何将 Azure DevOps 管道上的 .properties 文件设置为某种环境变量?
- sql - 如何返回嵌套的 JSON 数组
- angular - 在星云寄存器组件中添加自定义字段
- sas - SAS中的朴素贝叶斯分类器
- javascript - 使用 Highcharts 映射 json 数据的问题