简体   繁体   中英

Regex to match optional parameter

I'm trying to write a regex to match an optional parameter at the end of a path.
I want to cover the first 4 paths but not the last one:

/main/sections/create-new
/main/sections/delete
/main/sections/
/main/sections
/main/sectionsextra

So far I've created this:

/\/main\/sections(\/)([a-zA-z]{1}[a-zA-z\-]{0,48}[a-zA-z]{1})?/g

This only finds the first 3. How can I make it match the first 4 cases?

You may match the string in question up the optional string starting with / with any 1 or or more chars other than / after it up to the end of the string:

\/main\/sections(?:\/[^\/]*)?$
                ^^^^^^^^^^^^^^

See the regex demo . If you really need to constrain the optional subpart to only consist of just letters and - with the - not allowed at the start/end (with length of 2+ chars), use

/\/main\/sections(?:\/[a-z][a-z-]{0,48}[a-z])?$/i

Or, to also allow 1 char subpart:

/\/main\/sections(?:\/[a-z](?:[a-z-]{0,48}[a-z])?)?$/i

Details

  • \\/main\\/sections - a literal substring /main/sections
  • (?:\\/[^\\/]*)? - an optional non-capturing group matching 1 or 0 occurrences of:
    • \\/ - a / char
    • [^\\/]* - a negated character class matching any 0+ chars other than /
  • $ - end of string.

JS demo:

 var strs = ['/main/sections/create-new','/main/sections/delete','/main/sections/','/main/sections','/main/sectionsextra']; var rx = /\\/main\\/sections(?:\\/[^\\/]*)?$/; for (var s of strs) { console.log(s, "=>", rx.test(s)); }

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