How to modify search and replace (regex) macro by Nige_S to process each line of selected text

The brilliant @Nige_S posted this macro to search and replace selected text using regex (I made minor changes)
I would like to apply the regex to each line of selected text.
thank you very much

Search and Replace Regex Current Selection.kmmacros (4.3 KB)

set theInstance to system attribute "KMINSTANCE"
tell application "Keyboard Maestro Engine"
	set theFind to getvariable "Local__Find" instance theInstance
	set theReplace to getvariable "Local__Replace" instance theInstance
	set theText to get the clipboard
	set the clipboard to (search (get the clipboard) for theFind replace theReplace with regex and process tokens)
end tell

The AppleScript method is really for when you are already executing an AS and want to leverage the KME to do a search and replace -- AS doesn't have a good built-in way of doing that, especially for regex. Otherwise it's a lot of overhead for little gain when you are already in a macro -- just use the "Search and Replace" action.

@noisneil sparked a good thread and did some great work a while ago, using a prompt to drive the search and replace, so may want to chime in here.

The AS is just using the KM action, so the search and replace behaves just like it does in KM. As written it is global, finding and changing every found instance, so it is applied to every line.

If you mean "I want ^ and $ to match the start and end of the line, not the start and end of the entire text" -- as it is the KM Search and Replace it uses the same option at the start of the pattern: (?m). So

(?m)^The\s.*$

...would match the entirety of every line beginning with "The ".

1 Like

I am working on selected text, so I solved the problem (or rather you solved the problem) by this simple modification.
Does this make sense to you ?
Funny: I had tried to solve the problem myself, and had tried with ?m without the parenthesis which did not work. Why the parentheses ?
thank you very much

Well remembered, @Nige_S! Here are all the text manipulation subroutines I ended up with:

Text Submacros.kmmacros (625.2 KB)

2 Likes

thank you !

1 Like

Because (? at the start of the pattern means "Here come some options" and the ) finishes the options section.

Without the parentheses the pattern is invalid because ?m would mean "zero or one of the preceding character, then an m" -- but there is no preceding character...

1 Like

thank you !