How to match a word based on slash in regular expression

Mario R

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?

Wiktor Stribiżew

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to make a regular expression match based on a condition?

regular expression to match word-word or word

javascript regular expression to not match a word

Regular expression to match not containing a word

How do I make this regular expression not match anything after forward slash /

How to check for "/" slash in XML with Regular Expression

Regular expression, match a partial word, C#

Regular expression to match a word but not inside backticks

Greedy match in MS Word regular expression?

Python regular expression match whole word

Python regular expression match whole word

regular expression to match exact word with boundries

Regular expression: Match everything after a particular word

Regular expression to match beginning letter of second word

Regular Expression to match word NOT preceded with a period

Regular expression to match a word or its prefix

Regular Expression to match two similar word

A regular expression to match and exclude word/string

Function to match a word in a string on a regular expression in MySQL

Regular Expression to match statement that contain word 'abc'

Regular Expression: match word in a blank of a sentence

Slash in regular expression in Golang

How to match data with a regular expression

How to match regular expression In Javascript

How to write IF AND regular expression match

How To Limit A Regular Expression Match

Regular expression to filter lines based on a word combination

Create new column based on regular expression match

Elasticsearch string based query to match a regular expression