[SOLVED] Search and replace up until second to last character

I have this path:
/Users/myusername/folder1/folder2/folder2/file.txt

I want to save a variable that will just include the file name and the parent folder so I would get this:
folder2/file.txt

At this point I'm comfortable with basic RegEx, but this seems to be more complex.
This things I found online are either for other things, or they are too complicated for me to modify it to fit my case.
Any tips?

I just had this light bulb moment, don't know why...
So I got to this .*(\/.*\/.*)$
It seems to match what I need to match, but I had to include the second to last /
How can I match everything up to that without including it?
I could add another search and replace and just remove that character, but I wonder if there's a way to include that in the original Regex?

And is my solution a good one or do you have any other way of doing it?

Another light bulb moment haha
I just needed to include the / in the first group like this:
(.*\/)(.*\/.*)$

So now I guess I need to use that action that converts the regex into groups individually, right? That way I can just use the last group, which is what I need.

Yes, it's working! :muscle:

image

1 Like

Keyboard Maestro Variable Arrays (specifying "/" as the custom delimiter) allow us to express this directly, without needing regular expressions or search and replace.

Assuming that the file path is called local_FP:

  • the file name is %Variable%local_FP[-1]/%, and
  • the parent name is %Variable%local_FP[-2]/%

so, placing a literal / between the two tokens:

File name and parent from full path.kmmacros (2.6 KB)


%Variable%local_FP[-2]/%/%Variable%local_FP[-1]/%

4 Likes

Let me enjoy my victory... come on! haha

Thanks for sharing that. I will definitely save that info. I didn't know about that.
It can be very useful indeed.

Learning RegEx is still valuable to me, because if I end up needing it outside KM, it's always good to understand how it works. And I'm glad I was able to find it :slight_smile:

Again, thanks for sharing that info. Super valuable :raised_hands:

1 Like