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.RegularE开发者_如何学JAVAxpressions.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.
*.
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 ^(?:\.?[^.]+|[^.]+\.)$
精彩评论