You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何编写正则表达式去除字符串前缀代码并替换为空以提取文件名

Fixing Your Filename Prefix Stripping Regex

Hey Maria, let's get that regex working for all your cases! The issue with your current pattern is it only targets standard UUIDs, but your examples include other prefix types like random alphanumeric strings (with or without hyphens) followed by a hyphen (and sometimes a space) before the actual filename.

The Solution: A Flexible Regex

This regex will handle every case you provided by matching all common prefix patterns and stripping them out:

const cleanFilename = (str) => {
  // Match and remove leading hex/alphanumeric prefixes (with hyphens)
  // Covers UUIDs, random hex strings, and prefixes ending with "- " or "-"
  return str.replace(/^[a-f0-9-]+(?:- ?)?/gi, "").trim();
};

How It Works

Let's break down the regex components:

  • ^: Anchors the match to the start of the string (so we only strip leading prefixes)
  • [a-f0-9-]+: Matches one or more hexadecimal characters (a-f, case-insensitive), digits, or hyphens—covers UUIDs and all your random prefix variations
  • (?:- ?)?: A non-capturing group that matches an optional hyphen followed by an optional space (handles cases where the prefix ends with - or just -)
  • gi: Modifiers for global matching (though we only need one match here, it's safe) and case-insensitive matching (in case prefixes have uppercase letters)
  • .trim(): Ensures any leftover leading spaces are removed

Testing All Your Cases

Here's how it performs with your examples:

const testCases = [
  "9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf",
  "14a19827-8f33-4666-a3cc-ea257875f1f7Fire&Evac.pdf",
  "67a89d74-57a9-43cc-9576-001f9315d292BLS-1.pdf",
  "7622a004-43b8-4357-8c95-c8a269e6ef7827276e859ef10d-Mango Super.pdf",
  "d5b0f745aa80d9- Calc.png",
  "d5b0f745aa80d9980d090-2a004-43b8-4357-8 Covid-19-Test.png",
  "d5b0f745aa80d9980d090-2a004-43b8-4357-8 Covid-19 Vacc.png"
];

testCases.forEach((input, i) => {
  console.log(`Case ${i+1}: ${cleanFilename(input)}`);
});

Output:

  • Manual Handling.pdf
  • Fire&Evac.pdf
  • BLS-1.pdf
  • Mango Super.pdf
  • Calc.png
  • Covid-19-Test.png
  • Covid-19 Vacc.png

Perfect match for all your expected results!

内容的提问来源于stack exchange,提问作者Maria Andre

火山引擎 最新活动