Selaa lähdekoodia

add CleanFileName

KngStr 2 vuotta sitten
vanhempi
commit
f5400a29cd
1 muutettua tiedostoa jossa 32 lisäystä ja 0 poistoa
  1. 32 0
      Source/ksString.pas

+ 32 - 0
Source/ksString.pas

@@ -26,6 +26,11 @@ function AutoChangeFileName(AFile: string): string;
 /// 自动替换文件名中的非法字符为
 /// </summary>
 procedure ChangeInvalidFileNameChars(var FileName: string; AChar: Char = '_');
+/// <summary>
+/// 清理文件名中的 (1) [1]
+/// (1)系统命名,[1]浏览器下载命名,甚至[1] (2)
+/// </summary>
+function CleanFileName(const Filename: string): string;
 
 /// <summary>
 /// 格式化秒为时间,冒号分割
@@ -168,6 +173,33 @@ begin
   end;
 end;
 
+function CleanFileName(const Filename: string): string;
+var
+  s: string;
+  i: integer;
+begin
+  Result := ExtractFileName(Filename);
+  Result := ChangeFileExt(Result, '');
+
+  // 处理 () 情况
+  s := Copy(Result, Length(Result) - 2, 3);
+  if (Copy(s, 1, 1) = '(') and (Copy(s, Length(s), 1) = ')') then begin
+    i := StrToIntDef(Copy(s, 2, 1), 0);
+    if (10 > i) and (i > 0) then
+      Result := Copy(Result, 1, Length(Result) - 3);
+  end;
+
+  // 处理 [] 情况
+  s := Copy(Result, Length(Result) - 2, 3);
+  if (Copy(s, 1, 1) = '[') and (Copy(s, Length(s), 1) = ']') then begin
+    i := StrToIntDef(Copy(s, 2, 1), 0);
+    if (10 > i) and (i > 0) then
+      Result := Copy(Result, 1, Length(Result) - 3);
+  end;
+
+  Result := Trim(Result);
+end;
+
 function FormatSeconds(const AValue: Double): string; overload;
 var
   h, m, s, ms: Integer;