How can I use regexes to split strings by multiple delimiters, with a limit?

I have a rather unusual requirement for splitting. I need to use something like the limit option of var1, var2 = string.split(delimiter, limit). However, string.split doesn't support multiple delimiters, which I need it to do. Therefore, I need to use re.split. How can I put a limit on re.split or otherwise acheive this splitting?

Ideally, the I would be able to input something like

contents = "Sentence? Sentence! Another sentence."

And have the two output vars be:

var1 = "Sentence"
var2 = "Sentence! Another sentence."

2 answers

  • answered 2018-07-11 05:33 Ignacio Vazquez-Abrams

    >>> re.split('[?!.]', "Sentence? Sentence! Another sentence.", maxsplit=1)
    ['Sentence', ' Sentence! Another sentence.']
    

  • answered 2018-07-11 05:44 Aemyl

    Here's a solution without regex (valid answer for the original question):

    delimiters = '?!.'
    contents = "Sentence? Sentence! Another sentence."
    first = contents
    second = ''
    for delimiter in delimiters:
        try:
            first, after = first.split(delimiter, 1)
            second = after + second
        except ValueError:
            pass
    print((first, second))
    
    [Out]
    ('Sentence', ' Sentence! Another sentence.')