I'm struggling with a regex to capture a string from the clipboard but remove the trailing whitespaces
Input "A frog jumps into the pond "
Output "A frog jumps into the pond"
It looks easy (probably is!) but it's confounding me how to capture the spaces within the string, but remove the ones at the end.
Use the KM
Filter action instead:
See the KM wiki for more info action:Filter [Keyboard Maestro Wiki]
Ah! Thank you. I've not seen this before.
I'd also just figured out that if you copy a line of text in Microsoft Word, that has no trailing space, it adds one! This wasn't helping.
Anywy, thanks for being so quick with a response, I'm off to check it out!
Yeah that was absolutely what I need, and a massively useful new KM thing I learned. Thank you so much
Be aware that it will also trim leading whitespace, including tabs.
It might help to look at why your regex didn't work as intended. By default, matches are "greedy" and capture as many characters as possible. So even though you've anchored your pattern to the end of the string with
$ it matches "as many characters of any kind as possible (
.*) followed by zero or more whitespace characters (
\s*) then the string end".
"As many as possible of anything" plus the option of zero whitespace means your capture group is the entire string, including any trailing whitespace.
You can get round that by making your first capture group "non-greedy", using the
? modifier, but leaving the whitespace capture "greedy":
(.*?)\s*$ -- "as few characters as possible until the trailing whitespace, followed by as much of the whitespace as possible".
That's not a direct result of your pattern -- it's either something else in the macro or Word's not-so-Smart Paste messing things up for you.
Also worth noting that
- Prefixing a variable with
temp may flag it as temporary to you, but as far as KM is concerned it's still a Global and so is persistent and available everywhere. If you want a transitory variable use either
Instance. More about that in the "Scope" section of the manual
- You don't need a variable at all! You can "Search and Replace" on the system clipboard and your transformed string is ready to paste:
...using the same regex, the "replace to Source" part being "and replace the entire contents of the clipboard with the first capture group (
\1) of the regex".