简体   繁体   中英

Regex to match mostly alphanumeric paths

I tried creating a regular expression to verify path names for a filesystem API I write using GridFS.

My current RegEx ^[A-Za-z0-9\\-\\[\\]()$#_./]*$ can fulfill this criteria:

  • Allow az , AZ , 0-9 , -[]()$#_./

However it doesn't meet these additional criteria:

  • First Character has to be /
  • There mustn't be any occurrence of multiple / in a row.

Questions:

  • Can anybody help me fix my RegEx?
  • Are there any possible issues for using my criteria for path names? (Did I miss anything important?)

Not sure about the path criteria, but regarding the RegExp, pretty simple:

^\/(?!\/)([A-Za-z0-9\-\[\]()$#_.]|(\/(?!\/)))*$

\\/(?!\\/) means a slash / not followed by a slash (?!\\/) . I used it twice, once as the first character, and again as one of the possible matches after the first character.

Here's how you could address your requirements. To enforce the first character is / , simply add that after the ^ .

^\\/[A-Za-z0-9\\-\\[\\]()$#_./]*$

To not allow consecutive slashes, you should remove it from your character set, and think of the set as a portion of the path. Portions would be separated by a slash. So the final regex would be:

^\\/([A-Za-z0-9\\-\\[\\]()$#_.]\\/?)*$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM