That is correct. And we have made an Enhancement Request to allow us to set the KM Replace Action to replace ONLY the first match:
Request: Add Switch to KM Search/Replace to Turn Global Matches On/Off
The simplest way is to use JavaScript for Automation (JXA) taking advantage of the native JavaScript RegEx function:
The actual JavaScript command is just one line:
sourceStr.replace(RegExp(reFind), replaceStr)
All of the work is getting the KM Variables into the script.
But this is a completely reusable script using Local Variables, so you can store it somewhere (like in your KMFAM library) and easily use whenever you need it.
Example Output
Below is just an example written in response to your request. You will need to use as an example and/or change to meet your workflow automation needs.
Please let us know if it meets your needs.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MACRO: Regex Replace ONLY First Match Using JXA [Example]
-~~~ VER: 1.0 2021-07-10 ~~~
Requires: KM 8.2.4+ macOS 10.11 (El Capitan)+
(Macro was written & tested using KM 9.0+ on macOS 10.14.5 (Mojave))
DOWNLOAD Macro File:
Regex Replace ONLY First Match Using JXA [Example].kmmacros
Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.
ReleaseNotes
Author.@JMichaelTX
PURPOSE:
- Regex Replace ONLY First Match Using JXA [Example]
- Since KM Does NOT Offer a Replace of only the First Match, we much use a script.
HOW TO USE
- First, make sure you have followed instructions in the Macro Setup below.
- See the below "How to Use" Comment Action
- This macro is just an example written in response to your request. You will need to use as an example and/or change to meet your workflow automation needs.
MACRO SETUP
- Carefully review the Release Notes and the Macro Actions
- Make sure you understand what the Macro will do.
- You are responsible for running the Macro, not me. ??
.
Make These Changes to this Macro
- Assign a Trigger to this Macro .
- Move this macro to a Macro Group that is only Active when you need this Macro.
- ENABLE this Macro, and the Macro Group it is in.
- For more info, see KM Wiki article on Macro Activation
.
- For more info, see KM Wiki article on Macro Activation
- REVIEW/CHANGE THE FOLLOWING MACRO ACTIONS:
(all shown in the magenta color)- SET Source String
- Set RegEx Find Pattern
- SET REPLACE String
REQUIRES:
- KM 9.0+ (may work in KM 8.2+ in some cases)
- macOS 10.12.6 (Sierra)+
TAGS: @Example @RegEx @Replace
==USE AT YOUR OWN RISK==
- While I have given this a modest amount of testing, and to the best of my knowledge will do no harm, I cannot guarantee it.
- If you have any doubts or questions:
- Ask first
- Turn on the KM Macro Debugger from the KM Status Menu, and step through the macro, making sure you understand what it is doing with each Action.