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

关于使用正则表达式一步完成字符串必要子串校验与合法路径名判定(含参数提取)的问询

使用正则表达式一步完成字符串必要子串校验与合法路径名判定(含参数提取)的问询

Absolutely! You can absolutely pull this off in a single regex step—validating the path is properly formatted, ensuring it has at least one parameter marker (:), and even extracting those parameter names all at once. Let me walk you through how to do this:

Here's what the regex needs to handle:

  • Reject any path that doesn't have at least one : (like your path1/path2/path3 example)
  • Make sure every segment of the path (split by /) only uses your allowed characters: [a-zA-Z0-9.~!$&'()*+,;=@-_\s:]
  • Capture all the parameter names (the text that comes after :)

The working regex:

For most modern regex engines (like those in Python, JavaScript, or Java), this regex will do everything in one go:

^(?=.*:)(?:(?:[a-zA-Z0-9.~!$&'()*+,;=@-_\s]+)|:(?<param>[a-zA-Z0-9.~!$&'()*+,;=@-_\s]+))(?:/(?:(?:[a-zA-Z0-9.~!$&'()*+,;=@-_\s]+)|:(?<param>[a-zA-Z0-9.~!$&'()*+,;=@-_\s]+)))*$

How it breaks down:

  1. ^(?=.*:): This is a positive lookahead that checks the path has at least one : right away—so any path without parameters gets rejected immediately.
  2. The main pattern matches each path segment: either a regular segment made of allowed characters, or a parameter segment starting with : that captures the parameter name into a named group param.
  3. (?:/...) repeats this pattern for every subsequent segment separated by /.
  4. $ ensures we match the entire string, so there's no extra invalid characters sneaking in.

Testing with your examples:

  • :param1/path1/:param2: Passes validation, and captures param1 and param2 in the param groups.
  • path1/path2/path3: Fails the initial lookahead (no : present), so it's rejected.
  • path1/:param1: Passes validation, and captures param1 as the only parameter.

Quick notes:

  • If your regex engine doesn't support named groups, just replace (?<param>...) with (...) to use unnamed capture groups.
  • I included whitespace (\s) in the allowed characters as per your requirement—if that was a mistake, just remove \s from all the character classes.
  • This regex ensures every single segment follows your character rules, so a path like path1/!@#/param would get rejected because !@# includes disallowed characters.

Yep, this all works in one single regex step—validation and parameter extraction wrapped up together!

备注:内容来源于stack exchange,提问作者Андрей

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 02:54:40