Question

Given a list of strings, I'm interested in finding which ones are valid http:// URLs. My first approach would be to use a regex and do something like this:

var urls = strs.Where(str => urlRegex.matches(str));

Is there a more idiomatic/natural/simple way to do it?

Was it helpful?

Solution

You can use the parsing built in to the System.Uri Class to validate the Urls. This has the benefit of correctly handling query strings included with the Url, and should be able to parse any string that .Net can use as a Url.

After using TryCreate to attempt parsing each string, check that the Uti.Scheme property is an HTTP uri (otherwise a filesystem path would also pass the filter).

OTHER TIPS

Yes I would use Uri.TryCreate and then test the Scheme property of successfully parsed URI's to ensure it is HTTP.

However, if the URI's you were looking for are substrings of a larger block of text, regex is the way to go.

I would go for the regex based approach and your approach looks fine to me

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top