Lin Ma
Lin Ma

Reputation: 10159

regular expression for a tree hierarchy string extraction

suppose I have tree hierarchy string like this "/grand_parent/parent/child" (three level) or "/parent/child" (two level), "/child" (one level) and I tried "^(/[^/]*)" could extract the first level "/grand_parent", and wondering if I want to extract the first two levels if there exists, e.g.

what is the suggested regular expression?

Upvotes: 0

Views: 179

Answers (2)

Toto
Toto

Reputation: 91528

Why not just ^/[^/]+/[^/]+?

Demo

Upvotes: 0

Emma
Emma

Reputation: 27743

My guess is that maybe you'd want to design an expression similar to:

^(?=\/[^\/]+\/[^\/]+)(\/[^\/]+\/[^\/]+)

not sure though:

Demo 1

which would work the same without the capturing group:

^(?=\/[^\/]+\/[^\/]+)\/[^\/]+\/[^\/]+

Demo 2

Escapings are just for the demos.

Upvotes: 1

Related Questions