What is the C# & .NET Regex Pattern that I need to use to get "bar" out of this url?
http://www.foo.com/bar/123/abc
In ATL regular expressions, the pattern would have been
http://www\.foo\.com/{[a-z]+}/123/abc
Simply: #http://www\.foo\.com/([a-z]+)/123/abc#
use parenthesis instead of brackets.
You will need to use a character on the front and the end of the regular expression to make it work too.
Here is a solution that breaks the url up into component parts; protocol, site and part. The protocol group is not required so you could give the expression 'www.foo.com/bar/123/abc'. The part group can contain multiple sub groups representing the folders and file under the site.
^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$
You would use the expression as follows to get 'foo'
string s = Regex.Match(@"http://www.foo.com/bar/123/abc", @"^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$").Groups["part"].Captures[0].Value;
The breakdown of the expression results are as follows
protocol: http://
site: www.foo.com
part[0]: bar
part[1]: 123
part[2]: abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With