Regex match exact amount of character on multi line string
Question:
I have a text something like below.
start
foo1
bar1
stop
start
foo2
bar2
stop
start
oof
rab
stop
I need to capture text between start and stop but only starting with only four white spaces. So I want to capture first and third part of the text. Can you help please?
I wrote something like this. dotall is active (dot matches new line)
r's{4}start.*?s{4}stop'
But it doesn’t work. It still captures all blocks. ^ doesn’t work since all text is behaving a single line.
Answers:
Set the regex flags this way:
- Use single line flag (
re.S
) so the .
matches newlines;
- Use
re.M
so that the ^
anchor matches with multiple lines.
Then:
r'^s{4}startb.*?^s{4}stopb'
works
I have a text something like below.
start
foo1
bar1
stop
start
foo2
bar2
stop
start
oof
rab
stop
I need to capture text between start and stop but only starting with only four white spaces. So I want to capture first and third part of the text. Can you help please?
I wrote something like this. dotall is active (dot matches new line)
r's{4}start.*?s{4}stop'
But it doesn’t work. It still captures all blocks. ^ doesn’t work since all text is behaving a single line.
Set the regex flags this way:
- Use single line flag (
re.S
) so the.
matches newlines; - Use
re.M
so that the^
anchor matches with multiple lines.
Then:
r'^s{4}startb.*?^s{4}stopb'
works