Mike
Mike

Reputation: 674

Regex for HTTP URL with Basic authentication

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.

^(.+?//)(.+?):(.+?)@(.+)$

Upvotes: 4

Views: 6842

Answers (2)

Cameron
Cameron

Reputation: 98746

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];

Upvotes: 5

Paolo Tedesco
Paolo Tedesco

Reputation: 57192

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+://)...

Upvotes: 7

Related Questions