简体   繁体   中英

C# Regex for Web.config Rewrite Url

I have the following url www.localproject.com:843/user/validate/eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9eyJ0ZW1wVXJsIjoie1wiQ3VzdG9tZXJJZFwiOjEsXCJDb3Vyc2VJZFwiOjEsXCJUb2tlblwiOm51bGwsXCJFeHBpcnlcIjpcIjIwMTgtMDQtMThUMTc6MzU6MTMuOTQ2MjM2NCswNTowMFwifSJ9uvm7jZ3us5UFa1hqh4bod2cSamcxF2rRUbfxs7DHQs

from which I need to extract only 10 to 30 characters after validate including numbers etc. For example, I need only this

eyJhbGciOiJodHRwOi8vd3d

what should be the regex? I tried following but it not working

^api/user/validate/(^([a-zA-Z\d]){50})

Try

api\/user\/validate\/(.{23})

Can see it working here - https://regex101.com/r/Xr6Ueo/1

You can do this with regex or Substring . If the string is stored in web.config you can still get to it with ConfigurationManager . I recommend taking the parts you do not need out of the Uri . This way once you deploy to prod there's less of a chance of things breaking down.

var input = new Uri("www.localproject.com:843/user/validate/eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9eyJ0ZW1wVXJsIjoie1wiQ3VzdG9tZXJJZFwiOjEsXCJDb3Vyc2VJZFwiOjEsXCJUb2tlblwiOm51bGwsXCJFeHBpcnlcIjpcIjIwMTgtMDQtMThUMTc6MzU6MTMuOTQ2MjM2NCswNTowMFwifSJ9uvm7jZ3us5UFa1hqh4bod2cSamcxF2rRUbfxs7DHQs");
var environmentAgnosticPath = input.Segments[input.Segments.Length - 1];//take just the part after /validate

//example output: eyJhbGciOiJodHRwOi8vd3d
//I don't know what you mean by 10 - 30 since the example is 23 characters
var resultFromSubstring = environmentAgnosticPath.Substring(0,23);

var pattern = @"[A-Za-z0-9]{10,23}";
Regex regex = new Regex(pattern);
var resultFromRegex = regex.Match(environmentAgnosticPath).Value;

And generally regex101 is a great playground for figuring out the regex part.

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