【问题标题】:How to reorder a string (no matter how it is) using Python REGEX如何使用 Python REGEX 重新排序字符串(不管它是怎样的)
【发布时间】:2020-09-30 14:03:20
【问题描述】:

我是玩 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

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

【问题讨论】:

  • 为什么是“for”而不是“four”?
  • 是否必须使用正则表达式?
  • 我建议你把你的字符串改成"one two three four"或者"one two three fire!"
  • 抱歉打错了哈哈.. 是的,不幸的是我认为这是强制性的

标签: python regex capturing-group


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你可以这样做:

    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
    

    【讨论】:

    • 您的正则表达式仅配置为“一二三为”。我正在尝试编写一个正则表达式,无论单词的顺序如何,它都会重新排列短语。
    • @EduardoFranco 已修复!
    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    相关资源
    最近更新 更多