Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

regex - Regular expression to match a valid absolute Windows directory containing spaces

I would like a regular expression to match a valid absolute Windows directory path, where directory names can contain spaces.

Example matches:

C:picturesholiday  (without trailing backslash)
C:picturesholiday (or with trailing backslash)
C: picturesholiday
C: picturesholiday
C:pictures  holiday
C:pictures  holiday
C:pictures holiday 

Example fails:

picturesholiday (no relative path allowed)
C:pictures*holiday (not a valid directory path)

I have tried ^[a-zA-Z]:(\w+)*([\])?$ but that does not match the spaces.

I have also tried ^[a-zA-Z]:(s)*(\w+)*(s)*([\])?$ but that works erratically.

Regular expressions are my last resort. I have also tried to validate the text box using a non-regex solution, like in this answer. But I have not found a method that works for spaces.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a regex that will work:

^[a-zA-Z]:\(((?![<>:"/\|?*]).)+((?<![ .])\)?)*$

It makes the path conform to the NTFS standard (see the MSDN spec). I'll break it down:

^[a-zA-Z]:\ matches single drive letter, with colon and backslash

(?![<>:"/\|?*]) is a negative lookahead to ensure the next character is not invalid

((?![<>:"/\|?*]).)+ wraps that lookahead, followed by the next character, any number of times

(?<![ .])\ is a negative lookbehind to ensure the file/directory doesn't end with a space or period. Please note: Lookbehinds are not fully implemented everywhere just yet.

All of that is is repeated 0 to many times, with the last backslash optional.

For many use cases it may be best to restrict the path length to 256 characters. To do so, replace *with {0,256}.

EDIT: allow root directory


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...