Search code examples
regexrex

REGEX: To extract particular string from path


I am looking to extract particular string from path.

For example, I have to extract 4th value separated by (.) from filename. which is "lm" in below examples.

Examples:

/apps/java/logs/abc.defgh.ijk.lm.nopqrst.uvw.xyz.log
/apps2/java/logs/abc.defgh.ijk.lm.log

This will extract full file name:

.*\/(?<name>.*).log

Solution

  • You can use

    .*\/(?:[^.\/]*\.){3}(?<value>[^.\/]*)[^\/]*$
    

    Or, if .log must be the extension:

    .*\/(?:[^.\/]*\.){3}(?<value>[^.\/]*)[^\/]*\.log$
    

    See the regex demo. Details:

    • .* - any zero or more chars other than line break chars, as many as possible
    • \/ - a / char
    • (?:[^.\/]*\.){3} - three occurrences of zero or more chars other than . and / as many as possible and a dot
    • (?<value>[^.\/]*) - Group "value": zero or more chars other than . and / as many as possible
    • [^\/]* - zero or more chars other than /
    • \.log - a .log substring
    • $ - end of string.