Regexp, find in a procedure last "end" to replace with another word

Viewed 44

I have tried to replace in all procedures some mistakes. Now, I need to find last "end;" in procedure and replace it with another text. I wrote like: (\s.*)(end|END)(.*(;).*) But in work not correctly, it also replace some words in the middle of the text. I using re biblio from python.

1 Answers

You can use

result = re.sub(r'(?si)(.*)\bend\b', r'\g<1>some other word', text)

The regex matches

  • (?si) - an inline re.DOTALL (s) and re.IGNORECASE (i) modifier
  • (.*) - Group 1: any zero or more chars as many as possible
  • \bend\b -a whole word end.

The \g<1>some other word replacement is the Group 1 value (I used \g<1> since it will be helpful if your some other word starts with a digit) plus your word.

NOTE: if your some other word can contain literal backslashes, do not forget to double them.

Related