This covers all spectrum catalogs, trailing or starting slashes.
Everyone else here is not yet ...
public static String extractFilename(String path) { java.util.regex.Pattern p = java.util.regex.Pattern.compile('^[/\\\\]?(?:.+[/\\\\]+?)?(.+?)[/\\\\]?$'); java.util.regex.Matcher matcher = p.matcher(path); if ( matcher.find() ) { return matcher.group(1); } return null; } println extractFilename("data\\\\path/to/file/RandomFile.pdf") println extractFilename("RandomFile.pdf") println extractFilename("RandomFile.pdf/") println extractFilename("data\\\\path/to/file/RandomFile.pdf/") println extractFilename("/data\\\\path/to/file/RandomFile.pdf/") println extractFilename("/data\\\\path/to/file/RandomFile.pdf") println extractFilename("/RandomFile.pdf") println extractFilename("/RandomFile.pdf/") println extractFilename("/")
Print
RandomFile.pdf RandomFile.pdf RandomFile.pdf RandomFile.pdf RandomFile.pdf RandomFile.pdf RandomFile.pdf RandomFile.pdf /
.................................................. .....................EDIT............................ ................................................
Explanation for Uday. It was quite difficult, and I'm not sure that today I can argue about all this, but I will try :)
^[/\\\\]?(?:.+[/\\\\]+?)?(.+?)[/\\\\]?$
0: Integer regex
^
1: starts with
[/\\\\]?
2: slash or backslash (yes, four slashes for one, crazy!). Once or not, therefore not required.
(?:.+[/\\\\]+?)?
3: This step is difficult. It is designed to skip everything except the last one, which corresponds to this exact scheme, not an exciting group (?: ... we searched for a character several times, and then one slash.
A group may repeat many times, but it is not greedy. Therefore, he talks about it, except when you agree with the following regular expression explained in 4.
This whole thing, though, is not required because of? outside parentheses. For example, "/RandomFile.pdf/" will not create a match here and continue with 4.
However, now I find it a little strange since. + greedy, yet he is looking forward to the slash for the match. It may be the nature of the groups that they are not greedy or a mistake in the syntax of the Java template.
(.+?)[/\\\\]?$
4: Since the regular expression applies to the entire line, it must also match to the end. The previous match in 3 was not greedy, reluctant, using + ?, which means that it will only match the regular expression after it does not match. Our word at the end of $ is in parentheses, which may or may not end with a slash. I decided to return the root path as the file name if the file name is missing, but just a slash, since this is also the file name (directory name)
5: Brackets are a hold group, and this is what we return at the end.
Hope this clarifies a bit.