Regex to find text between second and third slashes

后端 未结 6 1939
夕颜
夕颜 2020-11-29 07:48

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

相关标签:
6条回答
  • 2020-11-29 07:59

    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.

    0 讨论(0)
  • 2020-11-29 08:07

    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.

    0 讨论(0)
  • 2020-11-29 08:11

    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:

    /.*/(.*?)/
    
    0 讨论(0)
  • 2020-11-29 08:13
    /.*?/(.*?)/
    

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

    ([^/]*)/$
    

    Alternate split method:

    split("/")[2]
    
    0 讨论(0)
  • 2020-11-29 08:13

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

    anyways, here is regex pattern:

    /[\/]*[^\/]+[\/]([^\/]+)/
    
    0 讨论(0)
  • 2020-11-29 08:21

    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 =~ /\/[^\/]*\/([^\/]*)\//;
    
    0 讨论(0)
提交回复
热议问题