当掩码中包含“[”时,如何使用 TMask?
我一直在 Delphi 2010 中尝试 TMask ,它似乎按预期工作除非在一种情况下:当掩码名称包含 [ 或 ] 时,掩码似乎总是返回 false。例如:
var
MaskObj : TMask;
begin
MaskObj:= TMask.Create('c:\[test]\*');
try
Result:= MaskObj.Matches('c:\[test]\text');
finally
FreeAndNil(MaskObj);
end;
end;
返回 false。 ...
是的,[ 和 ] 是文件名中的合法字符。因此,如果我想排除 c:[test]* 中的所有文件,我可以在这里做什么?我唯一的解决方案是如果检测到 [ 则执行 StringReplace ,但这对于大量文件来说会慢:
if (pos('[', Mask)>0) then
begin
mask:= ReplaceString(Mask, '[','_', etc...
// and do the same for the file name---
end;
还有其他方法吗?
I have been experimenting with TMask in Delphi 2010 and it seems to work as expected except in one situation: when the mask name contains [ or ] the mask always seem to return false. For example:
var
MaskObj : TMask;
begin
MaskObj:= TMask.Create('c:\[test]\*');
try
Result:= MaskObj.Matches('c:\[test]\text');
finally
FreeAndNil(MaskObj);
end;
end;
returns false. ...
Yes, [ and ] are legal characters in file name. So if I want to exclude for example all files in c:[test]*, what could I do here? My only solution is to do a StringReplace if [ is detected, but this will be slow for a large number of files:
if (pos('[', Mask)>0) then
begin
mask:= ReplaceString(Mask, '[','_', etc...
// and do the same for the file name---
end;
Is there any other approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
'[' 用于标记一组字符的开始(例如,“[AZ]”)。为了单独匹配“[”,您只需将其创建为自己的单字符集。 ']' 不需要类似地转义,因为一旦找到前导 '[',它只是一个特殊字符。尝试
C:\[[]test]\*
编辑:
如果您允许任意掩码,则需要使用
StringReplace(Mask, '[', '[[]', [rfReplaceAll])
用于掩码,但不用于文件名。如果您从不使用[az]
通配符,我只会从 TMask 继承并在构造函数中处理它。'[' is used to mark the beginning of a set of characters (eg, "[A-Z]"). In order to match '[' on its own you just need to create it as its own single-character set. ']' doesn't need to be similarly escaped, since it's only a special character once a leading '[' is found. Try
C:\[[]test]\*
Edit:
If you're allowing arbitrary masks you'll need to use
StringReplace(Mask, '[', '[[]', [rfReplaceAll])
for the mask, but not for the filenames. If you never use the[a-z]
wildcards I'd just descend from TMask and handle it in the constructor.当您尝试使用
MatchesMask
作为路径时要非常小心。问题比这里暴露的问题还多。请参阅此博客文章了解详细信息。要修复它,您可以拆分路径和文件名(如果您的用例允许),将
Masks.pas
单元复制到项目目录中(以便进行编译,而不是“官方” 'Masks
单元)并禁用 '[' 处理,以避免速度损失。华泰
Be very careful when you try to use
MatchesMask
for paths. There are more problems than the one exposed here. See this blog post for details.To fix it, you could split the path and the file name (if your usage case allows it), copy the
Masks.pas
unit in your project directory (in order to be compiled instead of the 'official'Masks
unit) and disable the '[' processing, in order to have no speed penalties.HTH