[SOLVED] Regex question

Let's say I have a Finder path like this (but it could be anything that has a pattern):
/users/myusername/folder1/folder2/folder3/folder4

Now I want to group patterns that can easily by multiplied depending on the number inside the curly brackets, but the pattern itself is a capture group.

Similar to this
image

So in this case the pattern is text+slash (folder2/) and it then can be repeated multiple times by changing the number {2} and the pattern itself is a capture group.
So in this case the main pattern is folder2/, which I would like to be a capture group as folder2/folder2/, because of {2}

If I change it to {3}, the group would be folder1/folder2/folder2/ and so on...

Hope it's making sense what I'm trying to achieve?

Unless I'm misunderstanding, couldn't you just do this?

.../)(.*\/){%Variable%local_RepeatCount%}(.*)$

Change the variable's value, and you'll change the number in the regex.

-rob.

This is a regex question without necessarily including KM in the equation.
I would like to know how to achieve this without KM so I can learn a bit more how RegEx works.

But what you shared is not what I'm trying to achieve. The issue here is not the value inside {}.

What I'm trying to understand is how to create a group out of that pattern
(.*\/){2}
Doing this ((.*\/){2})didn't work. It still sees those two (the folder in blue and the folder in yellow/brown) as 2 different groups. I want them both to be seen as 1 group.

Basically I create a pattern, which in this case is (.*\/){x} and by changing x inside {}, the pattern extends, but always as a single group, not as 2, 3, 4 groups, etc.

Let's say the path is
Users/myname/cars/Europe/yellow/guitar/John/

By using this pattern as the "raw" pattern (.*\/)(.*\/){1}(.*)$, I get two groups (everything up to John and then John/). The last one, which is what I want to eventually use as a group, is John/, right?
Now if I change {1} to {2}, the pattern of "any character followed by a slash character" expands to guitar/John/. But I don't want guitar/ to be 1 group and John/ to be a second group. I want 1 group as guitar/John/.

Use a non-capturing group (?:...) and apply the {2} to that group, putting the entire thing inside a capturing group:

(.*\/)((?:.*\/){2})(.*)$

In your first example, the ((?:.*\/){2}) will capture folder1/folder2/

In your second example, the ((?:.*\/){2}) will capture guitar/John/

2 Likes

This is the solution: I totally misread what you were asking to do, and @roosterboy answer is what you want.

-rob.

Yes, that's it! Thank you! :muscle:

SCR-20240114-ufdz

SCR-20240114-ufge

SCR-20240114-ufhh

Keyboard Maestro's Filter action also rewards experimentation – it returns a number of named file-path components:

Screenshot 2024-01-15 at 5.54.54 pm

2 Likes