Regex for extracting folder name from absolute path(Linux)

Viewed 336

I am using regex function in Apache Nifi to find the folder name in file path but it doesn't seem to give me correct result

I want to parse out "state" and "date" with two different regex from this file path

/upload/main/state/02022021/

This was the regex i used

${ "absolute.path":replaceFirst( ".*[/\\\\]{1}([a-zA-Z]+)[/\\\\]{1}(\d{8}).?$", "$1") } ${"absolute.path":replaceFirst(".*(\d{8}).+$", "$1")}

3 Answers

You can consider using

state = ${"absolute.path":replaceFirst(".*[/\\\\]([^\\\\/]+)[/\\\\]\\d{8}[/\\\\]?$", "$1")}
date  = ${"absolute.path":replaceFirst(".*[/\\\\](\\d{8})[\\\\/]?$", "$1")}

See regex demo #1 and regex demo #2.

The point is to

  1. Make sure the regex matches the entire input string
  2. Make sure each backslash that creates a regex escape (like \d, \\) is also escaped
  3. Put parentheses around the part of a match you want to extract
  4. Use $1 in the replacement to extract that part.

Here is the first pattern description:

  • .* - any zero or more chars other than line break chars, as many as possible
  • [/\\] - a / or \ char
  • (\d{8}) - Capturing group (referred to with the help of $1 from the replacement pattern): eight digits
  • [\\\\/]? - an optional / or \ char
  • $ - end of string.

I would use these two expressions if the occurrences are always in the same place:

  • for the date in last position (?<=\/)[^\/]*?(?=\/$)
  • for state in the second to last position (?<=\/)[^\/]*?(?=\/[^\/]*?\/$)

Also, you can change .* for something more specific to increase reliability.

If you are interested only in getting values and nothing specific with approach then try below,

state = ${absolute.path:getDelimitedField(4, '/')}
date  = ${absolute.path:getDelimitedField(5, '/')}

Refer -Nifi Expression Language

Related