Creating a regular expression to match file paths can depend on the specific format and conventions of the file paths you want to match. Here's a general example for matching common file paths on Unix-like systems (including Linux and macOS) and Windows:
// Regular expression for matching file paths const filePathRegex = /^(\/[^\0]+|([a-zA-Z]:\\|\\\\)([^\\\/:*?"<>|\r\n]+[\\\/])+)[^\\\/:*?"<>|\r\n]+$/; // Test cases const unixFilePath = "/path/to/file.txt"; const windowsFilePath = "C:\\Users\\Username\\Documents\\file.txt"; console.log(filePathRegex.test(unixFilePath)); // true console.log(filePathRegex.test(windowsFilePath)); // true
Explanation:
^: Asserts the start of the string.(\/[^\0]+|([a-zA-Z]:\\|\\\\)([^\\\/:*?"<>|\r\n]+[\\\/])+): This part of the regular expression matches either a Unix-like path starting with / or a Windows path starting with a drive letter (C:\ or \\ for network paths).[^\\\/:*?"<>|\r\n]+: Matches the file or directory name, excluding certain characters that are not allowed in file names.[\\\/]: Matches the directory separator (\ or /).[^\\\/:*?"<>|\r\n]+: Again, matches the file or directory name.$: Asserts the end of the string.Adjust the regular expression based on your specific requirements, such as supporting different formats, handling special characters, or accommodating platform-specific conventions.
Regular expression to match Unix-style file paths.
^\/(?:[\w-]+\/)*[\w.-]+$
Regular expression to match Windows-style file paths.
^[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+$
Regular expression to match file paths on both Unix and Windows.
^(?:[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+|\/(?:[\w-]+\/)*[\w.-]+)$
Regular expression to match relative file paths.
^(?:\.{1,2}\/)*(?:[\w-]+\/)*[\w.-]+$ Regular expression to match absolute and relative file paths.
^(?:[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+|\/(?:[\w-]+\/)*[\w.-]+|\.{1,2}\/(?:[\w-]+\/)*[\w.-]+)$ Regular expression to match file paths with optional file extension.
^(?:[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+|\/(?:[\w-]+\/)*[\w.-]+|\.{1,2}\/(?:[\w-]+\/)*[\w.-]+)(?:\.\w+)?$ Regular expression to match file paths excluding certain characters.
^(?:[a-zA-Z]:\\(?:[^\\/:*?"<>|]+\\)*[^\\/:*?"<>|]+|\/(?:[^\\/:*?"<>|]+\/)*[^\\/:*?"<>|]+|\.{1,2}\/(?:[^\\/:*?"<>|]+\/)*[^\\/:*?"<>|]+)(?:\.\w+)?$ \/:*?"<>|.Regular expression to match file paths with a specific extension.
^(?:[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+|\/(?:[\w-]+\/)*[\w.-]+|\.{1,2}\/(?:[\w-]+\/)*[\w.-]+)\.txt$ .txt, allowing both absolute and relative paths.Regular expression to match file paths with a variable-length extension.
^(?:[a-zA-Z]:\\(?:[\w-]+\\)*[\w.-]+|\/(?:[\w-]+\/)*[\w.-]+|\.{1,2}\/(?:[\w-]+\/)*[\w.-]+)\.\w{1,5}$ Regular expression to match file paths with subdirectories up to a certain depth.
^(?:[a-zA-Z]:\\(?:[\w-]+\\){0,2}[\w.-]+|\/(?:[\w-]+\/){0,2}[\w.-]+|\.{1,2}\/(?:[\w-]+\/){0,2}[\w.-]+)(?:\.\w+)?$ finance set-intersection django-templates mediaelement select ini microsoft-dynamics negative-number jaxb2 relational-database