How to Count the Words in the First Line of Text in the Clipboard?

I am trying to count the number of words in the first line of the clipboard (there are always multiple lines) up to a ":". I think begins as a regex question but I am not sure where to start. Typically, there are 2 or 3 words, a colon, and then some more text. I just need to know how many words come before the colon.

If I can get the text before the colon into a variable, I know I can filter the variable with a word count. But how to select all the text before the variable in the first line?

I am getting closer. On regex101.com, this expression will capture everything on the first line up to the colon:
^.*?(?=:)

Unfortunately, KM is not returning anything with that expression.

Hi Heather, try out this macro to see if it works for you.

-Chris

Macro screenshot (click to expand/collapse)

Count words behind first colon on first line of clipboard.kmmacros (4.2 KB)

ss-601

Eureka! It works! Thank you.

The RegEx expression ^(.*): did the trick.

One of my goals this year was to learn RegEx. It has been a deeply rewarding experience. Each time I think of a new way to try and use it, I am amazed at what it can do.

Outstanding! You‘re very welcome. I have spent the better part of this last year really delving into RegEx and it has proven extremely useful.

As you‘re probably aware, you can use RegEx as a trigger for Keyboard Maestro macros. :wink:

-Chris

(Puts on "Regex Party Pooper" hat.)

Because you want "all the text up to the first :" (and assuming there always is a :) you can split the text on the : character, get the first "bit", and count the words in that.

Words Before First Colon.kmmacros (1.7 KB)

It looks complicated because it's all being done in one line, but breaking it down:

  • Split the System Clipboard on : and get the first item: %SystemClipboard[1]:% -- you can read more about "Variable Arrays" here
  • Use the WORDS() function to get the number of words in the first item: WORDS(%SystemClipboard[1]:%) -- more about functions here
  • Because we're using a function in a text field we have to wrap it in a %Caculate% token: %Calculate%WORDS(%SystemClipboard[1]:%)% -- more about the Calculate token here
3 Likes

This'll break if there's more than one : in the line -- since we only want the first, try a non-greedy match: ^(.*?):

(Which is what you call "learning from your own embarrassing mistakes" :wink: And what's the betting I've made another one here?)

2 Likes

I like it! I am assuming there is only one colon per line since she mentioned “text... a colon... and some more text”, but it makes sense to use a non-greedy match anyway.