Search code examples
regexseoisapi

Friendly Blog Url Isapi Rewrite Regex


My regex isn't great, and I'm struggling here. I need regex to get title from these 2 formats:

http://domain.com/blog/title
http://secure.com/domainkey/blog/title

but not match anything from (where subfolders could be multiple):

http://domain.com/images/blog/imagename
http://domain.com/images/subfolders/blog/imagename
http://secure.com/domain/images/blog/imagename
http://secure.com/domain/images/subfolders/blog/imagename

Any ideas? Thanks.


Solution

  • (http:\/\/(?:(?:secure.com\/domainkey)|(?:domain.com))\/blog\/)([\w-]+)
    

    capture two parts:

    1. base url, http://domain.com/blog/ or http://secure.com/domainkey/blog/
    2. the title

    demo with js:

    var regex = /(http:\/\/(?:(?:secure.com\/domainkey)|(?:domain.com))\/blog\/)([\w-]+)/ig;
    
    regex.exec('http://domain.com/blog/blog-title');
    // results: ["http://domain.com/blog/blog-title", "http://domain.com/blog/", "blog-title"]
    
    regex.exec('http://secure.com/domainkey/blog/blog-title')
    // results: ["http://secure.com/domainkey/blog/blog-title", "http://secure.com/domainkey/blog/", "blog-title"]
    

    assumed that blog title only contains [a-zA-Z_-], if you have more characters to capture, please modify the last part of the regex.