Saturday 15 January 2011

Python regex search lines that end with a colon and all text after until next line that ends with colon -



Python regex search lines that end with a colon and all text after until next line that ends with colon -

i have next text:

test 123: bluish auto test: auto not bluish auto yellowish hello: not test

i want set regex finds items start test or hello , precede colon, , optionally tree digit number, , homecoming content after until next line fits same description. above text, findall regex homecoming array of:

[("test", "123", "\nthis bluish car\n"), ("test", "", "\nthis auto not blue\n\nthis auto yellow\n"), ("hello", "", "\nthis not test")]

so far got this:

r = re.findall(r'^(test|hello) *([^:]*):$', test, re.multiline)

it matches each line according description i'm unsure how capture content until next line ends colon. ideas?

you utilize below regex uses dotall modifier,

(?:^|\n)(test|hello) *([^:]*):\n(.*?)(?=\n(?:test|hello)|$)

demo

>>> import re >>> s = """test 123: ... ... bluish auto ... ... test: ... ... auto not bluish ... ... auto yellowish ... ... hello: ... ... not test""" >>> re.findall(r'(?s)(?:^|\n)(test|hello) *([^:]*):\n(.*?)(?=\n(?:test|hello)|$)', s) [('test', '123', '\nthis bluish car\n'), ('test', '', '\nthis auto not blue\n\nthis auto yellow\n'), ('hello', '', '\nthis not test')]

python regex

No comments:

Post a Comment