Reformatting extracted substrings using Match.Result in C# .NET

Say you have the following Uri:

http://localhost:8080/webapps/bestapp

…and you’d like to extract the protocol and the port number and concatenate them. One option is a combination of a regular expression and matching groups within the regex:

Read more of this post

Reformatting extracted substrings using Match.Result in C# .NET

Say you have the following Uri:

http://localhost:8080/webapps/bestapp

…and you’d like to extract the protocol and the port number and concatenate them. One option is a combination of a regular expression and matching groups within the regex:

private static void ReformatSubStringsFromUri(string uri)
{
	Regex regex = new Regex(@"^(?<protocol>\w+)://[^/]+?(?<port>:\d+)?/");
	Match match = regex.Match(uri);
	if (match.Success)
	{
		Console.WriteLine(match.Result("${protocol}${port}"));
	}
}

The groups are defined by “protocol” and “port” and are referred to in the Result method. The result method is used to reformat the extracted groups, i.e the substrings. In this case we just concatenate them. Calling this method with the URL in above yields “http:8080”.

However you can a more descriptive string format, e.g.:

Console.WriteLine(match.Result("Protocol: ${protocol}, port: ${port}"));

…which prints “Protocol: http, port: :8080”.

View all posts related to string and text operations here.

Advertisement
Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: