简体   繁体   中英

RegEx for getting path and filename from code requiring path

I been searching for the RegEX to extract files with path from code, so that I could check if they exists but ended up not getting exactly what I wanted. This I guess is most likely due to lack of RegEX knowledge.

I got a bit frustrated about every single RegEx example I ran, I always ended up getting filenames of files without Paths, my requirements are fairly simple in sed kinda way.

/"+/{1,6}+.myext"/

I the path needs between 1-6 deep, it needs to be filename with certain extension, the path are unix based but not starting always starting with forward slash. And the filename cannot start with a dot.

I tried this in powershell and it works, I'm sure you can use something like this in your app.

$Matches = @()
$String = '/this/is/a/long/path/and/Filename.MyExtension'
if ($String -match '^(/?[^/]+){1,6}/([^/.][^/]*[.]MyExtension)$') {
    $Matches[2]
    } # end if

yields

Filename.MyExtension

This works by looking for between 1 and 6 groups of strings each string must start with a / and the string continues through all non slash characters or the character group must not start with a /

The last group of characters must not start with a / or . followed by all the non slash characters upto the required dot extension [in this case "MyExtension']

I know that this is late for the OPs question, but something that will be of help to the OP and to others trying to use RegEx is regexlib.com ; they have a large library of Regular Expressions. They also have a RegEx tester which is very helpful in testing your RegEx code. Also Ultrapico's Expresso is a very useful tool for creating regular expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM