Regex to find text between second and third slashes

I would like to capture the text that occurs after the second slash and before the third slash in a string. Example:

/ipaddress/databasename/

I need to capture only the database name. The database name might have letters, numbers, and underscores. Thanks.


How you access it depends on your language, but you'll basically just want a capture group for whatever falls between your second and third "/". Assuming your string is always in the same form as your example, this will be:

/.*/(.*)/

If multiple slashes can exist, but a slash can never exist in the database name, you'd want:

/.*/(.*?)/

/.*?/(.*?)/

In the event that your lines always have / at the end of the line:

([^/]*)/$

Alternate split method:

split("/")[2]

The regex would be:

/[^/]*/([^/]*)/

so in Perl, the regex capture statement would be something like:

($database) = $text =~ m!/[^/]*/([^/]*)/!;

Normally the / character is used to delimit regexes but since they're used as part of the match, another character can be used. Alternatively, the / character can be escaped:

($database) = $text =~ /\/[^\/]*\/([^\/]*)\//;

You can even more shorten the pattern by going this way:

[^/]+/(\w+)

Here \w includes characters like A-Z, a-z, 0-9 and _

I would suggest you to give SPLIT function a priority, since i have experienced a good performance of them over RegEx functions wherever it is possible to use them.


you can use explode function with PHP or split with other languages to so such operation.

anyways, here is regex pattern:

/[\/]*[^\/]+[\/]([^\/]+)/