简体   繁体   中英

Regular expression to allow file with only .txt or no extension

I need a regular expression that should allow files only with .txt or with no extension.

For example: c:\\document\\assignment\\test.txt or c:\\document\\assignment\\testing

This is what I have thus far:

^[a-zA-Z]:(\\\\[a-zA-Z0-9\\p{Space}[\\p{Punct}&&[^\\Q\\/:*?\"<>|\\E]]\\(\\)]+[^\\.])+(?=(\\.txt|\\.TXT))(\\.txt|\\.TXT)$

The above is working only for the .txt but not for files with no extension.

The regular expression requires the case-insensitive flag, and should work with most regex engine flavors.

^(?:[a-z]:|\\|\.{1,2})(?:\\[^<>:"/\\|?*.]+)+(?:\.txt)?$

REY

Explanation

The regular expression produces a match by matching the following sub patterns.

  • Start of the string
  • Find the start of a path: either a drive letter, a back-slash for a unc name, or one or two periods for a relative path
  • At least one path item that starts with a backslash and follows basic conventions from Naming Files, Paths, and Namespaces .
  • Optionally ending in .txt
  • End of the string.

You can simplify the expression if you don't need unc or relative paths by changing to first capture group to just az . You can add more extensions by changing the last capture group. For example, (?:\\.(txt|exe|com)? would match .txt , .exe , or .com .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM