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 capt
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.
I know you specifically asked for regex, but you don't really need regex for this. You simply need to split the string by delimiters (in this case a backslash), then choose the part you need (in this case, the 3rd field - the first field is empty).
cut
example:
cut -d '/' -f 3 <<< "$string"
awk
example:
awk -F '/' {print $3} <<< "$string"
perl
expression, using split
function:
(split '/', $string)[2]
etc.
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]
you can use explode
function with PHP
or split
with other languages to so such operation.
anyways, here is regex pattern:
/[\/]*[^\/]+[\/]([^\/]+)/
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 =~ /\/[^\/]*\/([^\/]*)\//;