File & Path
Relative Path
Matches relative file paths (./, ../, or path/to/file).
Try it in RegexPro →Available in
JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("^(\\.{1,2}\\/)?([^\\/\\0]+\\/)*[^\\/\\0]+$", "");
const input = "./src/index.ts";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
pyPython
import re
pattern = re.compile(r"^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$")
input_text = "./src/index.ts"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$`)
input := `./src/index.ts`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
regexengine-agnostic
^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$Raw source: ^(\.{1,2}\/)?([^\/\0]+\/)*[^\/\0]+$
How it works
`^(\.{1,2}\/)?` optionally matches `./` or `../` prefix. `([^\/\0]+\/)*` matches zero or more directory segments. `[^\/\0]+$` matches the final file segment.
Examples
Input
./src/index.tsMatches
./src/index.ts
Input
../parent/file.jsMatches
../parent/file.js
Input
file.txtMatches
file.txt
Common use cases
- •Import resolution
- •Build tools
- •Path normalization
Related patterns
Windows File Path
File & PathMatches absolute Windows file paths (e.g., C:\Users\file.txt).
Unix File Path
File & PathMatches absolute Unix/Linux file paths.
File Extension
File & PathCaptures the file extension from a filename.
Image File Extension
File & PathMatch common image file extensions: jpg, jpeg, png, gif, webp, svg, avif, bmp, ico, tif, tiff.