Using KM to Split a URL at the Question Mark, and Keep The First Half?

Hi All, Thanks in advance for the help. This may be a semi-noob question, and if so, my apologies. I’m looking to use Keyboard Maestro to:

  1. take the system clipboard (which, when I engage the macro, will contain a long URL with a question mark somewhere in it),
  2. chop the URL at the question mark, and
  3. set the first part (before the question mark) to a variable

For example: maybe I’ve copied the following URL to the clipboard:

All I care about is the part before the “?”. So in this case:

I feel like the answer is something like, “Cut the URL at the question mark, and keep the first part”, but I couldn’t figure that out.

Alternatively I played around with “Change the question mark to a space (which creates two ‘words’) and then keep only the first part”. But couldn’t make that work either. I tried a couple regex things but kept only getting “http”.

Any help someone can provide here would be much appreciated! Thanks.

Hey Tim,



Capture 1 to your variable name.

Best Regards,

Fantastic! This worked perfectly. This will save me 10-15 minutes a day, pretty much every weekday. Thanks very much.

Hey Tim,


I meant to explain that just a little.

Probably you went wrong because you were fooling with "?" which is a reserved character in regex.


^	== Beginning of line
(	== Start of Capture
https	== Literal String
?	== Zero or 1 of the preceding character
://	== Literal String
[^?]	== Range - Any character NOT '?'
+	== One or more
)	== End of Capture
\?	== Literal Question mark - made by escaping the ? with  a backslash.

A simpler way of doing this if you need only the text before the '?' is to find/replace.

In your case I'd probably capture the url to a variable and then search/replace in the variable.





Of course this little job is easy to do with AppleScript too:

set AppleScript's text item delimiters to "?"
tell application "Keyboard Maestro Engine"
  set myURL to the clipboard
  if myURL starts with "http" and myURL contains "?" then
    set urlFront to text item 1 of myURL
      set value of variable "myVar" to urlFront
    on error
      make new variable with properties {name:"myVar", value:urlFront}
    end try
    error "Malformed string in clipboard!"
  end if
end tell

Best Regards,


Thanks Tim for posting the question (I won’t use it as much as you, but I do manually strip the cruft off URLs when I paste them, and I’d never thought of using KM for this) and Chris for posting the how to (I really need to learn regex).

I’ve made a slightly modified version, more suitable for casual use. It’s simply a variation on the standard paste shortcut, which strips the cruft from a full URL already copied to the clipboard when pasted.