Python (re)

Windows File Path in PY

Matches absolute Windows file paths (e.g., C:\Users\file.txt).

Try it in the PY tester →

Pattern

regexPY
^[A-Za-z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$

Python (re) code

pyPython
import re

pattern = re.compile(r"^[A-Za-z]:\\\\(?:[^\\\\/:*?\"<>|\\r\\n]+\\\\)*[^\\\\/:*?\"<>|\\r\\n]*$")
input_text = "C:\Users\John\file.txt"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

`^[A-Za-z]:\\` matches the drive letter and root backslash. `(?:[^\\/:*?"<>|\r\n]+\\)*` matches directory segments. Final segment (the file or folder name) is allowed to be empty.

Examples

Input

C:\Users\John\file.txt

Matches

  • C:\Users\John\file.txt

Input

D:\

Matches

  • D:\

Input

/unix/path

No match

Same pattern, other engines

← Back to Windows File Path overview (all engines)