Regex for relative filepath maximum size and maximum Folder name size

1.4k Views Asked by At

Linux has a maximum filename length of 255 characters for most filesystems, and a maximum path of 4096 characters. If the foldername is longer than 255 it cannot be created.

/^[a-z0-9\s_@-/.]+$/i is a good regex (I need special characters in the path also), but I need to modify it, so that it limits the string length to 4095 and the folder name length to 255.

So limiting it is no issue /^[a-z0-9\s_@-/.]{1-4095}$/i ,but that still doesn't solve the maximum folder name size issue.

Sample that should validate:
/whatever/thisisnotapornstash/StillNot255CharactersButTheNextFolderIs/BPLrmwQRjm‌​twIGEMDcgGk1BCRY6ZkKzsHoWqJNzGxCzlGTSZkfOei0QD2S3bGfqSMJMPxuvgHhUJotNgh3hGDYD01n5‌​6JiZy32JygaHHDLQbGWtkbFJy5BrMP5s6eL6V8Kcft71CxHZUMEEJ2LbYExYtPxaWuQ9USUCxbt7wTIjA‌​LoLN6aHW0GovD5euXWsYuOsqvyGuzJqjaohM9FFNmMz7ul0R4HxzTWWQqCZ8hp6O2yipRTs5k4RmGCTLf‌​nY/

What I have come up with until now: data-ng-maxlength="4095" (This solves the filepath maximum length) data-ng-pattern=/^[a-z0-9\s_@/.-] (This is where I should limit the maximum character number to 255 between two slashes.)

Here is where I am testing it: https://regex101.com/r/kV7dL2/3

3

There are 3 best solutions below

0
On BEST ANSWER
/^\/?(([0-9a-z]{0,255})||([0-9a-z]{1,255})?([0-9a-z]{1,255}\/)+)[0-9a-z]{1,255}\/?$/i

This regex will test if all the folder names in the path are between 1 and 255 characters long. The forward slashes from the beginning/ending of the path are optional.

6
On

You need to use a comma to separate minimum and maximum values in the limiting quantifier (otherwise, {1-4095} matches literally the sequence of characters {1-4095}):

/^[a-z0-9\s_@/.-]{1,4095}$/i

Also, the hyphen must be at the end in order to avoid escaping it and match a literal hyphen.

2
On

How about:

/^(?=(?:\/[[email protected]]{1,255})+).{1,4095}$/i

The lookahead limits the length of directories to 255 characters then we test that the total length is limited to 4095 char.

You may use more generic regex like:

/^(?=(?:\/[^/]{1,255})+).{1,4095}$/i