Simple RegEx Capture

I want to do a simple thing: capture text before and after the word "and" and output them in reverse order. The pictured macro would be a start, but the interface doesn't offer me a place to capture the two strings, as in the very few, very thin examples I've managed to find. (Monstrously large examples are easy to find; simple ones are not.)

I expected to be able to enter "All", "One", and "Two" in the macro, but all I can get is "All" (or another name for the entire string). What am I missing?

Oops! I needed .+, not +. in both captures. Maybe I'll make progress now.

This is the user interface I get when I replicate your Search action:
KM 0 2021-09-09_23-05-44

What version of Keyboard Maestro are you using - I'm on 9.2?

See above. I had +. where I needed .+.

It made no difference having +. or .+ to me - I still got the user interface I showed you!

KM 0 2021-09-09_23-17-17

Are you saying it's all OK now?

It works now. Using +. didn't even start to work. Maybe you had the other version and changed the regex string rather than starting over?

Here's a working macro:

reverse order.kmmacros (2.8 KB)
image

Good try @DrMajorBob but I started with your version and then I created the version with the corrected regex!

Well, whatever happened the important thing is that it's working for you! Good job!

I've always been mightily annoyed that I have to copy the second thing, paste it before the first, and I still have to move and as well. Now I don't have to do that.

2 Likes

If you're trying to swap the two words on either side of "and" then the macro Super Swap will handle that for you.

3 Likes

That’s great, but fully baked over-complicated examples are not useful for learning the basics.

Hey Bobby,

I'm going to take a little different tack on this task.

When asking about parsing text one should always provide adequate samples of the before and after conditions of the text.

Sample 01:

one and two

Desired Outcome 01:

two and one

Sample 02 (selected text highlighted):

Some text one and two some more text.

Desired Outcome 02:

Some text two and one some more text.

I've added a starting sample to my macro, so user's don't have to monkey with providing it themselves and possibly make a mistake.

Since this is a simple find/replace task I've elected to use the Search and Replace Clipboard action.

I've also chosen to make the regular expression more precise (for better or worse).

Since you'll always know the initial condition of your selected text for this particular macro, there's nothing wrong with your regex – but there can be unintended consequences when using greedy quantifiers like .+.

See my regex explained on RegEx101.com.

As you can see I'm also pasting the result text instead of typing and deleting the past clipboard – these are techniques worth noting.

For learning regex I like the following tools:

-Chris


Swap Words 1 and 3 of 3 v1.00.kmmacros (5.8 KB)
Keyboard Maestro Export

2 Likes