关于使用正则表达式一步完成字符串必要子串校验与合法路径名判定(含参数提取)的问询
使用正则表达式一步完成字符串必要子串校验与合法路径名判定(含参数提取)的问询
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 yourpath1/path2/path3example) - 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:
^(?=.*:): This is a positive lookahead that checks the path has at least one:right away—so any path without parameters gets rejected immediately.- 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 groupparam. (?:/...)repeats this pattern for every subsequent segment separated by/.$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 capturesparam1andparam2in theparamgroups.path1/path2/path3: Fails the initial lookahead (no:present), so it's rejected.path1/:param1: Passes validation, and capturesparam1as 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\sfrom all the character classes. - This regex ensures every single segment follows your character rules, so a path like
path1/!@#/paramwould get rejected because!@#includes disallowed characters.
Yep, this all works in one single regex step—validation and parameter extraction wrapped up together!
备注:内容来源于stack exchange,提问作者Андрей
相关产品推荐
相关产品推荐

