【问题标题】:Is it possible to split a string on multiple delimiters in order?是否可以按顺序在多个分隔符上拆分字符串?
【发布时间】:2013-12-05 03:28:27
【问题描述】:

我知道如何使用 re 根据多个分隔符拆分字符串,如以下问题:Split Strings with Multiple Delimiters?。但我想知道如何使用分隔符列表中给出的顺序拆分字符串,其中每个拆分只会发生一次。

multiple_sep_split("hello^goo^dbye:cat@dog", ['^',':','@'])
>>> ['hello', 'goo^dbye', 'cat', 'dog']  #(note the extra carat)
multiple_sep_split("my_cat:my_dog:my:bird_my_python",[':',':','_'])
>>> ['my_cat','my_dog','my:bird','my_python']

一种方法可能是不匹配分隔符,而是匹配分隔符之间的文本并将它们作为组返回,但还有其他方法吗?

text_re = re.compile('(.+)^(.+):(.+)@(.+)') # get each group from here

【问题讨论】:

  • 您是否要求比您提供的正则表达式更好的方法?有什么问题吗?
  • 不清楚您要的是什么。用斜体字“按顺序”实际上并没有解释这对你意味着什么;-) 如果你指定了集合 (list? ) 您想到的分隔符 - 我们只能猜测。
  • 我马上更新!得去吃午饭了……!
  • @TimPeters 感谢您努力理解这个问题!我已经更新了它,希望它更有意义:)。

标签: python regex string


【解决方案1】:

如果我理解您的要求,您只需要一系列字符串 partition 操作:第一个分隔符上的第一个 partition ,然后是第二个,等等到最后。

这是一个递归方法(不使用re):

def splits(s,seps):
    l,_,r = s.partition(seps[0])
    if len(seps) == 1:
        return [l,r]
    return [l] + splits(r,seps[1:])

演示:

a = 'hello^goo^dbye:cat@dog'

splits(a,['^',':','@'])
Out[7]: ['hello', 'goo^dbye', 'cat', 'dog']

【讨论】:

    【解决方案2】:

    我认为您的问题严重不足,但至少在您给出的示例中给出了您想要的结果:

    def split_at_most_once_each_and_in_order(s, seps):
        result = []
        start = 0
        for sep in seps:
            i = s.find(sep, start)
            if i >= 0:
                result.append(s[start: i])
                start = i+1
        if start < len(s):
            result.append(s[start:])
        return result
    
    print split_at_most_once_each_and_in_order(
        "hello^goo^dbye:cat@dog", "^:@")
    

    返回['hello', 'goo^dbye', 'cat', 'dog']。如果您绝对想“聪明”,请继续寻找;-)

    【讨论】:

    • 看到我们独立地得出相同的变量名让我感到振奋。尽管您的函数名称显然更优越:)
    • 显然:splits 只能应用于香蕉 ;-)
    猜你喜欢
    • 2018-04-21
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多