Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# substring parse using regular expression (ATL >> NET)?

Tags:

c#

regex

atl

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
like image 966
bitcycle Avatar asked Aug 26 '26 12:08

bitcycle


2 Answers

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.

like image 104
Erick Avatar answered Aug 28 '26 01:08

Erick


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

like image 45
stevehipwell Avatar answered Aug 28 '26 02:08

stevehipwell