Home > Blockchain >  How to match a word based on slash in regular expression
How to match a word based on slash in regular expression

Time:07-26

I am trying to match a word with regex. for example, I want to match only first 2 folders in below string

/folder1/folder2/filder3/folder4/folder5

I wrote a below regex to match first two folders but it matches everything till /folder5 but I wanted to match only till /folder2

/(\w. ){2}

I guess . matches everything. Any idea how to handle this?

CodePudding user response:

You can use

^/[^/] /[^/] 
^(?:/[^/] ){2}

Or, if you need to escape slashes:

^\/[^\/] \/[^\/] 
^(?:\/[^\/] ){2}

See the regex demo. [^/] is a negated character class that matches any char other than a / char.

  • Related