Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for HTTP URL with Basic authentication

Tags:

c#

regex

url

In my application, I must read a URL and do something if the URL contains Basic authentication credentials. An example of such a URL is

http://username:[email protected]

Is the regular expression below a good fit for my task? I am to capture four groups into local variables. The URL is passed to another internal library that will do further work to ensure the URL is valid before opening a connection.

^(.+?//)(.+?):(.+?)@(.+)$
like image 886
Mike Avatar asked Sep 19 '25 23:09

Mike


2 Answers

It looks ok, and I think that a regular expression is good to use in this case. A couple of suggestions:

1) I think that named groups would make your code more readable, i.e:

^(?<protocol>.+?//)(?<username>.+?):(?<password>.+?)@(?<address>.+)$

Then you can simply write

Match match = Regex.Match(string, pattern);
if (match.Success) {
    string user = match.Groups["username"];

2) then you could make the expression a little more strict, e.g. using \w when possible instead of .:

^(?<protocol>\w+://)...
like image 113
Paolo Tedesco Avatar answered Sep 22 '25 13:09

Paolo Tedesco


Your regex seems OK, but why not use the thoroughly-tested and nearly-compliant Uri class? It's then trivial to access the pieces you want without worrying about spec-compatibility:

var url = new Uri("http://username:[email protected]");
var userInfo = url.UserInfo.Split(':');
var username = userInfo[0];
var password = userInfo[1];
like image 39
Cameron Avatar answered Sep 22 '25 12:09

Cameron