简体   繁体   中英

python re - split a string before a character

how to split a string at positions before a character?

  • split a string before 'a'
  • input: "fffagggahhh"
  • output: ["fff", "aggg", "ahhh"]

the obvious way doesn't work:

>>> h=re.compile("(?=a)")

>>> h.split("fffagggahhh")

['fffagggahhh']

>>>

Ok, not exactly the solution you want but I thought it will be a useful addition to problem here.

Solution without re

Without re:

>>> x = "fffagggahhh"
>>> k = x.split('a')
>>> j = [k[0]] + ['a'+l for l in k[1:]]
>>> j
['fff', 'aggg', 'ahhh']
>>> 
>>> rx = re.compile("(?:a|^)[^a]*")
>>> rx.findall("fffagggahhh")
['fff', 'aggg', 'ahhh']
>>> rx.findall("aaa")
['a', 'a', 'a']
>>> rx.findall("fgh")
['fgh']
>>> rx.findall("")
['']
>>> r=re.compile("(a?[^a]+)")
>>> r.findall("fffagggahhh")
['fff', 'aggg', 'ahhh']

EDIT:

This won't handle correctly double a s in the string:

>>> r.findall("fffagggaahhh")
['fff', 'aggg', 'ahhh']

KennyTM's re seems better suited.

import re

def split_before(pattern,text):
    prev = 0
    for m in re.finditer(pattern,text):
        yield text[prev:m.start()]
        prev = m.start()
    yield text[prev:]


if __name__ == '__main__':
    print list(split_before("a","fffagggahhh"))

re.split treats the pattern as a delimiter.

>>> print list(split_before("a","afffagggahhhaab"))
['', 'afff', 'aggg', 'ahhh', 'a', 'ab']
>>> print list(split_before("a","ffaabcaaa"))
['ff', 'a', 'abc', 'a', 'a', 'a']
>>> print list(split_before("a","aaaaa"))
['', 'a', 'a', 'a', 'a', 'a']
>>> print list(split_before("a","bbbb"))
['bbbb']
>>> print list(split_before("a",""))
['']

This one works on repeated a 's

  >>> re.findall("a[^a]*|^[^a]*", "aaaaa")
  ['a', 'a', 'a', 'a', 'a']
  >>> re.findall("a[^a]*|[^a]+", "ffaabcaaa")
  ['ff', 'a', 'abc', 'a', 'a', 'a']

Approach: the main chunks that you are looking for are an a followed by zero or more not- a . That covers all possibilities except for zero or more not- a . That can happen only at the start of the input string.

>>> foo = "abbcaaaabbbbcaaab"
>>> bar = foo.split("c")
>>> baz = [bar[0]] + ["c"+x for x in bar[1:]]
>>> baz
['abb', 'caaaabbbb', 'caaab']

Due to how slicing works, this will work properly even if there are no occurrences of c in foo .

split() takes an argument for the character to split on:

>>> "fffagggahhh".split('a')
['fff', 'ggg', 'hhh']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM