You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求用于验证Cloudinary Public ID的JavaScript正则表达式

Cloudinary Public ID Validation Regex in JavaScript

Let's nail this regex for validating Cloudinary Public IDs! First, let's recap the exact rules we need to enforce:

  • All printable characters are allowed except the reserved characters: ? & # \ % < > .
  • Cannot start or end with a space ( ) or slash (/)

Why Your Original Regex Failed

Your initial attempt ^[^\s\\]+[^?&amp;#\%&lt;&gt;]+$ had a few key issues:

  • You used HTML entities like &amp; instead of raw characters (&) — regex doesn't parse HTML entities
  • It didn't exclude the reserved character .
  • It didn't account for the "no slash at start/end" rule
  • The structure required at least two characters, which misses valid single-character Public IDs

The Correct Regex

Here's a regex that covers all the requirements, with clear logic:

const cloudinaryPublicIdRegex = /^(?![\s/])(?!.*[\s/]$)(?!.*[\?&#\\%<>.]).+$/;

Breakdown of the Regex

Let's break down each part to understand how it works:

  • ^(?![\s/]): Ensures the string doesn't start with a space or slash
  • (?!.*[\s/]$): Makes sure the string doesn't end with a space or slash
  • (?!.*[\?&#\\%<>.]: Checks that no reserved characters appear anywhere in the string
  • .+: Requires at least one character (since empty Public IDs aren't valid)

Test Cases

Let's verify with some examples:

  • ✅ Valid: my-profile_photo、blog/posts summer-vacation、custom-id!@$
  • ❌ Invalid: my-id (starts with space)、photos/ (ends with slash)、image?.png (contains ?)、file.name (contains .)

Alternative Concise Version

If you prefer a more compact regex without lookaheads (though slightly less readable), you can use this:

const cloudinaryPublicIdRegex = /^[^\s/?&#\\%<>](?:[^\?&#\\%<>]*[^\s/?&#\\%<>])?$/;

This works by:

  • Matching a valid start character (not space, slash, or reserved)
  • Allowing any number of non-reserved characters in the middle
  • Ending with a valid character (same rules as the start)
  • The ? makes the middle+end part optional, supporting single-character IDs

内容的提问来源于stack exchange,提问作者steve-o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:35:34