Regex: Match start of line in certain portion of text

Viewed 49

I want to match the start of line character only in certain portion of the text. Example text:

start of text
    line 1
      line 2

line 3
  line 4

stop matching after this
line 5
    line 6

line 7

And this is the substitution and output I am looking for:

start of text
line 1
line 2

line 3
line 4

stop matching after this
line 5
    line 6

line 7

So, I want to match spaces at the start of line, only till I hit the line -

stop matching after this

All I was able to do so far is (^\s+), but this matched all spaces at the start of line.

regex101 has my attempt and the testing data.

I am using this in Python.

2 Answers

Here is one approach using re.sub with a callback function. First, we can capture the text in between the two markers. Then, we can do another selective regex replacement to strip all leading whitespace from each line of this capture text.

inp = """start of text
    line 1
      line 2

line 3
  line 4

stop matching after this
line 5
    line 6

line 7"""

output = re.sub(r'\bstart of text\b([\s\S]*?)\bstop matching after this\b', lambda m: 'start of text' + re.sub(r'\r?\n[ ]+', '\n', m.group(1)) + 'stop matching after this', inp)
print(output)

This prints:

start of text
line 1
line 2

line 3
line 4

stop matching after this
line 5
    line 6

line 7

You do not need any regex to get what you want. Just lstrip() every line before the line that starts with your expected text:

s='start of text\n    line 1\n      line 2\n\nline 3\n  line 4\n\nstop matching after this\nline 5\n    line 6\n\nline 7'
res = []
stop = False  # Flag to know where to stop matching
for line in s.splitlines():
    if line.strip().startswith('stop matching after this'):
        stop = not stop  # Reverse the flag
    if stop:
        res.append(line) # Add line as is
    else:
        res.append(line.lstrip()) # Add the line stripped from the left

print("\n".join(res))

See the Python demo. Output:

start of text
line 1
line 2

line 3
line 4

stop matching after this
line 5
    line 6

line 7
Related