regex.ts 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * 模式配置类型定义
  3. */
  4. type PatternConfig = readonly [key: string, pattern: string, defaultValue?: string];
  5. /**
  6. * 根据模式配置推断返回类型
  7. */
  8. type InferResultType<T extends readonly PatternConfig[]> = {
  9. [K in T[number] as K extends readonly [infer Key, ...any[]] ? Key : never]: K extends readonly [any, any, infer Default]
  10. ? Default extends string
  11. ? string
  12. : string | undefined
  13. : string | undefined;
  14. };
  15. /**
  16. * 分析函数 - 根据 patterns 参数类型确定返回类型
  17. * @param patterns 模式配置数组
  18. * @param value 要解析的字符串
  19. * @returns 解析后的对象,类型根据patterns自动推断
  20. */
  21. export function analysis<T extends readonly PatternConfig[]>(patterns: T, value?: string): InferResultType<T> {
  22. const regex = patterns.map(([key, pattern]) => `(?:${key}:(?<${key}>${pattern})[;$]?)?`).join('');
  23. const groups = (value || '').match(new RegExp(`^${regex}`))?.groups ?? {};
  24. return patterns.reduce((values, [key, _, defaultValue]) => {
  25. values[key as keyof InferResultType<T>] = (groups[key] ?? defaultValue) as any;
  26. return values;
  27. }, {} as InferResultType<T>);
  28. }