×
¥
查看详情
🔥 会员专享 文生文 代码生成

JavaScript正则表达式生成器

👁️ 80 次查看
📅 Dec 8, 2025
💡 核心价值: 本提示词专为JavaScript开发场景设计,能够根据用户提供的模式描述生成精确、高效的正则表达式解决方案。提示词采用专业开发者角色设定,确保生成的代码符合JavaScript最佳实践,同时提供详细的代码解释和使用示例。适用于表单验证、文本匹配、数据提取等多种Web开发场景,帮助开发者快速解决正则表达式编写难题。

🎯 可自定义参数(3个)

模式描述
需要匹配的具体模式描述
匹配场景
正则表达式的主要应用场景
输出语言
输出内容的语言偏好

🎨 效果示例

正则表达式代码

// 推荐:先对输入做 trim,再整串匹配
const USERNAME_RE = /^(?!.*__)[A-Za-z][A-Za-z0-9_]{1,14}[A-Za-z0-9]$/;

function isValidUsername(input) {
  const value = String(input).trim(); // 忽略首尾空格
  return USERNAME_RE.test(value);
}

// 可选(一次性容忍首尾空格):直接在正则中处理首尾空白
// const USERNAME_RE_WITH_SPACES = /^\s*(?!.*__)[A-Za-z][A-Za-z0-9_]{1,14}[A-Za-z0-9]\s*$/;
// 使用方式与上面类似

代码解释

  • 整体目标:整串匹配一个用户名(去掉首尾空格后),满足以下条件:
    • 以字母开头
    • 只包含字母、数字、下划线
    • 总长度 3–16
    • 不允许出现连续两个下划线“__”
    • 不能以下划线结尾

正则分解(以 USERNAME_RE 为例):

  • ^ 和 $:整串匹配的锚点,确保整个字符串完全匹配。
  • (?!.*__):负向前瞻,禁止任何位置出现两个连续下划线。
    • 说明:从字符串开头断言“后续任意位置不出现‘__’”,一旦出现则整体不匹配。
  • [A-Za-z]:第一个字符必须是英文字母(大小写均可)。
  • [A-Za-z0-9_]{1,14}:中间主体,允许字母、数字或下划线,长度 1–14。
    • 加上首字符和末尾字符合计长度:1 + [1..14] + 1 = [3..16]。
  • [A-Za-z0-9]:最后一个字符必须是字母或数字(不能是下划线),从而满足“不能以下划线结尾”。

关于忽略首尾空格:

  • 推荐做法是在代码中先执行 trim() 再用 USERNAME_RE 测试,逻辑清晰、可维护性更好。
  • 若希望一次性用正则处理,可使用 USERNAME_RE_WITH_SPACES,在首尾加入 \s* 来吞掉空白,但仍建议业务侧显式 trim。

使用示例

  1. 基础表单验证
console.log(isValidUsername('Alice_01'));      // true
console.log(isValidUsername('  Bob_2  '));     // true(被 trim 后验证)
console.log(isValidUsername('ab'));            // false(长度不足 3)
console.log(isValidUsername('1alex'));         // false(未以字母开头)
console.log(isValidUsername('alex__wu'));      // false(连续下划线)
console.log(isValidUsername('Kevin_'));        // false(以下划线结尾)
console.log(isValidUsername('abcdefghijklmnop')); // true(16 个字母)
console.log(isValidUsername('abcdefghijklmnopq')); // false(17 个字符超长)
  1. 表单提交前的前端校验
const inputEl = document.querySelector('#username');
const errorEl = document.querySelector('#username-error');

inputEl.addEventListener('input', () => {
  if (isValidUsername(inputEl.value)) {
    errorEl.textContent = '';
  } else {
    errorEl.textContent = '用户名需以字母开头,长度3-16,允许字母/数字/下划线,且不能有连续下划线或以下划线结尾。';
  }
});
  1. 批量数据清洗(去除空白并过滤非法用户名)
const rawList = [' Alice_01 ', 'ab', '1alex', 'ab__cd', 'JackMa', 'Jerry_'];
const cleanList = rawList.map(s => s.trim()).filter(s => USERNAME_RE.test(s));
console.log(cleanList); // ['Alice_01', 'JackMa']

注意事项

  • 仅限 ASCII 字母、数字和下划线:
    • 若需支持多语言字母(如中文、带重音字符等),可使用 Unicode 属性类(需加 u 标志):
      • 开头字母:[\p{L}]
      • 内容字符:[\p{L}\p{N}_]
      • 末尾字符:[\p{L}\p{N}]
      • 示例:/^(?!.*__)[\p{L}][\p{L}\p{N}_]{1,14}[\p{L}\p{N}]$/u
  • 建议对输入先做 trim,以避免被动在正则中处理空白,提升可读性。
  • 负向前瞻 (?!.*) 会对整串搜索“”,但用户名最大 16 字符,性能不是瓶颈。
  • 若后续需要允许连字符等其它符号,请同步更新:
    • 字符集(中间与结尾);
    • 结尾限制(确保不以特殊符号结束);
    • 连续符号限制(新增相应的负向前瞻)。

正则表达式代码

// Global extractor: captures full order id, date, and sequence in groups 1–3
const ORDER_ID_RE = /(?:(?<=\[)|(?<=")|(?<=')|(?<![\w-]))(ORD-(\d{8})-(\d{6}))(?:(?=\])|(?=")|(?=')|(?![\w-]))/g;

// Example extractor function
function extractOrders(text) {
  const results = [];
  for (const m of text.matchAll(ORDER_ID_RE)) {
    // m[1] = full order id, m[2] = date (YYYYMMDD), m[3] = sequence (6 digits)
    results.push({
      id: m[1],
      date: m[2],
      seq: m[3],
      index: m.index, // start index of the match (the order id itself)
    });
  }
  return results;
}

代码解释

  • Pattern: (?:(?<=\[)|(?<=")|(?<=')|(?<![\w-]))(ORD-(\d{8})-(\d{6}))(?:(?=\])|(?=")|(?=')|(?![\w-]))
  • Modifiers:
    • g (global): find all matches in the text.

Breakdown:

  • Left boundary assertion (?:(?<=\[)|(?<=")|(?<=')|(?<![\w-]))
    • (?<=\[)|(?<=")|(?<='): If the ID is wrapped, assert it is immediately preceded by [, " or '.
    • (?<![\w-]): Otherwise, ensure the ID is not glued to a word character or a hyphen on its left. This avoids partial matches inside longer tokens.
  • Main capture (ORD-(\d{8})-(\d{6}))
    • Group 1: ORD-YYYYMMDD-XXXXXX (the full order number).
    • Group 2: \d{8} (the date, 8 digits, no leap-year validation by design).
    • Group 3: \d{6} (the 6-digit sequence).
  • Right boundary assertion (?:(?=\])|(?=")|(?=')|(?![\w-]))
    • (?=\])|(?=")|(?='): If wrapped, assert the matching closing ], " or ' immediately follows.
    • (?![\w-]): Otherwise, ensure the right neighbor is not a word character or hyphen.

Notes on wrapper handling:

  • The ID may appear unwrapped, or wrapped by square brackets [...], single quotes '...', or double quotes "...".
  • The wrapper characters are not part of the match due to lookarounds, so Group 1 contains only the ID.
  • The lookarounds are fixed-width and efficient, and they keep capturing groups clean: only 3 groups, exactly as required.

使用示例

  1. Basic extraction from a mixed log:
const log = `
INFO created: ORD-20250101-000123
DEBUG payload: "ORD-20240229-123456" processed
WARN missing id 'ORD-20231231-654321'
OK list: [ORD-20240315-000001] and also ORD-20250101-888888 end
`;

const matches = extractOrders(log);
console.log(matches);
/*
[
  { id: 'ORD-20250101-000123', date: '20250101', seq: '000123', index: 15 },
  { id: 'ORD-20240229-123456', date: '20240229', seq: '123456', index: 39 },
  { id: 'ORD-20231231-654321', date: '20231231', seq: '654321', index: 83 },
  { id: 'ORD-20240315-000001', date: '20240315', seq: '000001', index: 117 },
  { id: 'ORD-20250101-888888', date: '20250101', seq: '888888', index: 153 }
]
*/
  1. Extract and normalize into a simple array of IDs:
const ids = Array.from(log.matchAll(ORDER_ID_RE), m => m[1]);
console.log(ids);
// ['ORD-20250101-000123', 'ORD-20240229-123456', 'ORD-20231231-654321', 'ORD-20240315-000001', 'ORD-20250101-888888']
  1. Post-filtering by date prefix (e.g., only 2025 orders):
const only2025 = [];
for (const m of log.matchAll(ORDER_ID_RE)) {
  if (m[2].startsWith('2025')) only2025.push({ id: m[1], date: m[2], seq: m[3] });
}
console.log(only2025);
// [{ id: 'ORD-20250101-000123', date: '20250101', seq: '000123' }, { id: 'ORD-20250101-888888', date: '20250101', seq: '888888' }]

注意事项

  • Lookbehind support: The pattern uses fixed-width lookbehinds (?<=/?<!). Most modern engines (Node.js 10+, recent Chrome/Edge/Firefox/Safari) support them. If you must support environments without lookbehind, use a two-pass approach:
    1. Find core IDs with /ORD-(\d{8})-(\d{6})/g,
    2. Then inspect the character before and after the match to accept plain, [...], '...', or "..." contexts.
  • Wrapper symmetry: This extractor ensures the ID is properly adjacent to a closing ], ' or ", or separated from word/hyphen characters. It does not strictly enforce that the opening and closing wrappers are the same character in a single, indivisible branch. In typical logs with well-formed wrappers this is sufficient for extraction. If strict pairing is required, consider a two-pass validation (as described above) or a parser that checks both sides explicitly.
  • Date validity: The date part is 8 digits as requested; it does not validate month/day ranges or leap years. If you need stricter date validation, apply an additional check after extraction.
  • Case sensitivity: The regex expects uppercase ORD-. If your logs may contain lowercase or mixed-case, add the i flag and optionally verify the prefix in code.

正则表达式代码

// 路径:/users/:id/photos/:photoId?
// 要求:id 与 photoId 为数字;photoId 可选;可忽略末尾斜杠;整串匹配;依次捕获 id 与 photoId

// 推荐:使用位置捕获,确保依次捕获 id(第1组)与 photoId(第2组)
const routeRe = /^\/users\/(\d+)\/photos(?:\/(\d+))?\/?$/;

// 可选(增强可读性,同时仍保持捕获顺序 1:id, 2:photoId)
// const routeRe = /^\/users\/(?<id>\d+)\/photos(?:\/(?<photoId>\d+))?\/?$/;

function parsePath(path) {
  const match = routeRe.exec(path);
  if (!match) return null;

  // 依次捕获:match[1] 为 id,match[2] 为 photoId(可能为 undefined)
  const id = parseInt(match[1], 10);
  const photoId = match[2] !== undefined ? parseInt(match[2], 10) : null;

  return { id, photoId };
}

// 简单测试
console.log(parsePath('/users/123/photos/456')); // { id: 123, photoId: 456 }
console.log(parsePath('/users/123/photos'));     // { id: 123, photoId: null }
console.log(parsePath('/users/123/photos/456/'));// { id: 123, photoId: 456 }
console.log(parsePath('/users/123/photos/'));    // { id: 123, photoId: null }
console.log(parsePath('/users/abc/photos'));     // null

代码解释

  • ^ 与 $:锚定字符串开始与结束,确保整串匹配(避免前后有多余字符)。
  • /users/:匹配固定路径前缀 /users/。
  • (\d+):
    • 第1个捕获组,匹配 id,仅允许数字(1 位或更多)。
  • /photos:匹配固定路径片段 /photos。
  • (?:/(\d+))?:
    • 非捕获分组 (?:...):仅用于结构化与可选性,不生成捕获组。
    • 其中的 /(\d+) 为第2个捕获组,匹配 /photoId(仅数字)。
    • 整体加 ? 表示 photoId 这一段是可选的。
  • /?:末尾可选斜杠,满足“忽略末尾斜杠”的要求。
  • 修饰符:无(不使用 g/i,因为需整串、区分大小写的路径匹配)。

匹配逻辑:

  • 路径必须以 /users/<数字>/photos 开始。
  • 可继续匹配 /<数字> 作为 photoId(可省略)。
  • 路径可有也可没有末尾斜杠。
  • 成功匹配时依次捕获:
    • 组1:id
    • 组2:photoId(可能为 undefined)

使用示例

  • 场景1:路由中间件参数解析

    const path = '/users/987/photos/321';
    const m = routeRe.exec(path);
    if (m) {
      const id = Number(m[1]);
      const photoId = m[2] ? Number(m[2]) : null;
      // 继续执行业务逻辑
    }
    
  • 场景2:统一解析函数(用于服务端或前端路由)

    function matchUserPhotoPath(path) {
      const m = routeRe.exec(path);
      if (!m) return null;
      return { id: Number(m[1]), photoId: m[2] ? Number(m[2]) : null };
    }
    
    console.log(matchUserPhotoPath('/users/42/photos'));      // { id: 42, photoId: null }
    console.log(matchUserPhotoPath('/users/42/photos/99/'));  // { id: 42, photoId: 99 }
    
  • 场景3:批量校验与提取

    const paths = ['/users/1/photos', '/users/2/photos/3', '/users/abc/photos'];
    const results = paths.map(p => {
      const m = routeRe.exec(p);
      return m ? { ok: true, id: +m[1], photoId: m[2] ? +m[2] : null } : { ok: false };
    });
    console.log(results);
    // [{ok:true,id:1,photoId:null},{ok:true,id:2,photoId:3},{ok:false}]
    

注意事项

  • 本正则只匹配纯路径,不包含查询字符串或哈希。例如若可能出现 /users/1/photos?x=1,请在匹配前先剥离查询/哈希部分,或扩展正则。
  • 数字格式:
    • 允许前导零(如 /users/001/photos/0002)。如需禁止或限制位数,可将 \d+ 改为更严格的模式(例如 [1-9]\d* 限制不以 0 开头;或 \d{1,9} 限制长度)。
  • 路径大小写敏感:/Users/ 与 /users/ 不等同。如需大小写不敏感,可在构造正则时添加 i 修饰符,但一般路由建议区分大小写。
  • 性能与安全:
    • 正则已通过 ^ 与 $ 锚定,结构线性、无灾难性回溯风险,适合在线请求实时匹配。
  • 若需可读性更高的命名捕获(现代环境支持),可使用命名组版本并通过 match.groups.id 与 match.groups.photoId 访问;但位置捕获依旧按顺序返回,满足“依次捕获 id 与 photoId”的要求。

示例详情

📖 如何使用

模式 1:即插即用(手动档)
直接复制参数化模版。手动修改 {{变量}} 即可快速发起对话,适合对结果有精准预期的单次任务。
加载中...
💬 模式 2:沉浸式引导(交互档)
一键转化为交互式脚本。AI 将化身专业面试官或顾问,主动询问并引导您提供关键信息,最终合成高度定制化的专业结果。
转为交互式
🚀 模式 3:原生指令自动化(智能档)
无需切换,输入 / 唤醒 8000+ 专家级提示词。 插件将全站提示词库深度集成于 Chat 输入框。基于当前对话语境,系统智能推荐最契合的 Prompt 并自动完成参数化,让海量资源触手可及,从此彻底告别“手动搬运”。
安装插件
🔌 发布为 API 接口
将 Prompt 接入自动化工作流,核心利用平台批量评价反馈引擎,实现"采集-评价-自动优化"的闭环。通过 RESTful 接口动态注入变量,让程序在批量任务中自动迭代出更高质量的提示词方案,实现 Prompt 的自我进化。
发布 API
🤖 发布为 Agent 应用
以此提示词为核心生成独立 Agent 应用,内嵌相关工具(图片生成、参数优化等),提供完整解决方案。
创建 Agent

🕒 版本历史

当前版本
v2.1 2024-01-15
优化输出结构,增强情节连贯性
  • ✨ 新增章节节奏控制参数
  • 🔧 优化人物关系描述逻辑
  • 📝 改进主题深化引导语
  • 🎯 增强情节转折点设计
v2.0 2023-12-20
重构提示词架构,提升生成质量
  • 🚀 全新的提示词结构设计
  • 📊 增加输出格式化选项
  • 💡 优化角色塑造引导
v1.5 2023-11-10
修复已知问题,提升稳定性
  • 🐛 修复长文本处理bug
  • ⚡ 提升响应速度
v1.0 2023-10-01
首次发布
  • 🎉 初始版本上线
COMING SOON
版本历史追踪,即将启航
记录每一次提示词的进化与升级,敬请期待。

💬 用户评价

4.8
⭐⭐⭐⭐⭐
基于 28 条评价
5星
85%
4星
12%
3星
3%
👤
电商运营 - 张先生
⭐⭐⭐⭐⭐ 2025-01-15
双十一用这个提示词生成了20多张海报,效果非常好!点击率提升了35%,节省了大量设计时间。参数调整很灵活,能快速适配不同节日。
效果好 节省时间
👤
品牌设计师 - 李女士
⭐⭐⭐⭐⭐ 2025-01-10
作为设计师,这个提示词帮我快速生成创意方向,大大提升了工作效率。生成的海报氛围感很强,稍作调整就能直接使用。
创意好 专业
COMING SOON
用户评价与反馈系统,即将上线
倾听真实反馈,在这里留下您的使用心得,敬请期待。

试用后开通会员即可无限使用

加载中...