Regex for matching everything before the "(" character?

What would be the regex for matching everything that occurs before the "(" character in a string?

This character would only occur once, so I'm not worried about which instance.

Assuming you want to capture everything before the ( into a variable, this does the trick:

image

2 Likes

No need, of course, for a regular expression – Keyboard Maestro Variable Arrays can have custom delimiters:

Before opening parenthesis.kmmacros (2.5 KB)


See: Variable Arrays

4 Likes

I tried both methods using a really long block of text, just to see how they compare:

Screenshot of macro

The parenthesis is just before "Libero," in the last block visible in the screenshot (though it's about halfway through the full text). And the results?

The regex split is ever so slightly faster. This used to surprise me, but the regex engine in KM (not sure if it uses Apple's library or Peter's own) is ridiculously speedy. Compared to starting a shell script or AppleScript action, it's a huge timesaver as it doesn't incur the overhead of starting an engine for the shell or AppleScript.

Obviously, this minor speed improvement wouldn't make a difference in a simple use like this, but might if you're doing hundreds of such splits over the course of the macro. For ease of use, the variable array method is the way to go; for speed and more flexibility in selecting the text you want, regex would win.

I personally use both methods depending on the task at hand.

-rob.

2 Likes

Human time or machine time ?

Run-time speed is an understandable proxy for quality – it's easy to measure – but I wonder whether the prevalence of its use doesn't underly quite a lot of software dysfunction ?

(The fastest-executing solution is seldom the most reliable, and often costs even more time in off-road rescue and maintenance than it consumed in lengthy composition and testing :slight_smile: )

Much faster to simply use the KM custom array than to experiment (and ask for help) with regular expressions.

1 Like

Quite possible. Personally, I'll use the more-readable solution even if it's slower, though I do my best now to minimize the calls to the shell script action: When I use it (which is still quite often), I try to set it up so that I can run multiple commands at once, to avoid the overhead cost associated with each call.

Most of my scripts aren't time sensitive, but in some (like the web search macro), every portion of a second the the pop-up window doesn't appear after you press the activation keys adds friction to using the tool. I spend a fair bit of time in those types of macros looking for portions of seconds.

-rob.

1 Like