Exit Python loop when replacement count is 0
- 
 When performing manual find/replace, the bottom of the dialog states how many occurrences were replaced. Is it possible to use some form of equivalent information in a Python script utilizing editor.rereplacein a loop, to exit when the last execution resulted in 0 replacements? If so, could someone provide an example? I’m not seeing any useful clues in the Python Script help.Example of code I want to have repeating in a loop: editor.rereplace(r'^(.+?) (\(tracks: .+?\)), (.+?) — (.+?)$', ur'\1 — \4 \2\r\n\3 — \4')
- 
 One technique you could use is to get the text of the document into a variable before the replacement (e.g. temp = editor.getText()), then get the text after the replacement, and see if it is the same as the saved variable, e.g.if editor.getText() == temp. If so, you know that the replacement replaced nothing.
- 
 This may also be of interest: Feature request: editor.rereplace() could return number of replacements made. 
- 
 Maybe it goes without saying that you could get the match count before doing the replacement – and of course if the match count is zero then you can break out of your loop before doing a replacement that wouldn’t replace anything: while True: matches = [] editor.research(your_regex, lambda m: matches.append(m.span(0))) if len(matches) == 0: break editor.rereplace(your_regex, ...)
- 
 All great ideas that I didn’t think of, and I like that last one the most, so I think I’ll go with it. Thanks much, Alan! 
- 
 @M-Andre-Z-Eckenrode said in Exit Python loop when replacement count is 0: I like that last one the most A modification to that one could be to limit the matches that research()will look for to 1, e.g.:editor.research(your_regex, lambda m: matches.append(m.span(0)), 0, pos1, pos2, 1)The last argument of 1 will limit the possible matches to 1, which is sufficient to determine that there are matches remaining. This could speed up a slow running regex by not looking for things you don’t need. 
- 
 @Alan-Kilborn said in Exit Python loop when replacement count is 0: A modification to that one could be to limit the matches that research()will look for to 1, e.g.:Noted, and I like it. Thanks again. 

