简体   繁体   中英

translating filename wildcards to regex

I need to translate arbitrary good old DOS wildcard strings to regex strings, which then are to be used with System.Text.RegularExpressions.Regex . Unfortunately, my regex knowledge is quite embarrassing.

I'm trying to wrap my head around stuff like *.* , .* , and *. . My current problem is that *. is generally expected to match files that either end with a dot or have no dot at all.
So I translate *. into ^.+[^\\.].*$ , but this is apparently wrong. It not only matches blah and blah. , but also blah.blah .

So what's the correct regex syntax to match blah and blah. , but not blah.blah ?

I think the following will work for you

^[^.]+\.{0,1}$

from start of string match any character but . and the string may end with 0 or 1 .'s

I can't seem to create a file whose name ends with a dot, but I have observed that the glob *. will match a name that starts with a dot, if the name has no other dots in it. For example, it matches .cvspass , but not .antelope.cfg . It also matches names with no dots at all. The regex for that would be ^\\.?[^.]+$ .

The "ends with" equivalent would be ^[^.]+\\.?$ , but I don't think you need that. If you also need to match at start or end (but nowhere else), you can use ^\\.?[^.]+\\.?$ . If the two conditions are mutually exclusive, use ^(?:\\.?[^.]+|[^.]+\\.)$

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