简体   繁体   中英

Regex issues with url rewriting

I'm using RegEx in C#/ASPNET Core 2.0 for URL Rewriting. Basically I need to match this:

blocked\/([a-z]{1,3})\/?([a-zA-Z0-9]+)\/(.*)\/?

However, it's not working as expected. I need to match the following:

/blocked/en/test1/
/blocked/en/test1/test2/
/blocked/en/test1/test2
/blocked/en/
/blocked/eN/test1

match 1: en match 2: test1 match 3: test2

If match 2 or 3 is missing, or just 3, I still want to match. So the following should be:

/blocked/en/test1/ - MATCH en, test1
/blocked/en/test1/test2/ - MATCH en, test1, test2
/blocked/en/test1/test2 - MATCH en, test1, test2
/blocked/en/ - MATCH en
/blocked/en/test1 - MATCH en, test1

I also need the trailing slash to be ignored. Basically any combination should match.

https://regex101.com/r/Bvm9yl/2/

Any suggestions, along with explanation, is welcomed. Thanks!

I think this is what you need:

(?<=\/blocked\/)([a-zA-Z]{1,3})\/(\w+)?\/?(\w+)?\/?

Demo

Expression Diagram:

在此处输入图片说明

The solution is quite simple in this case , It can be done in two steps :

Steps :

1. Extract the pattern using regex.
    pattern = "blocked\/.*"
2. Split the string based on "/" , and all take entries other than first i.e blocked

Hope this helps

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