Related Tags:
Asp.Net It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. Learn More, C# C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java. Learn More, ASP.NET MVC The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly. Learn More,

How to find all occurrences of strings between two strings or two keywords in C#?

Description:I need a method that will return list of strings which comes between two keywords,
For example:
If I have given following string to the method.
"<SomeString> This is first string </SomeString><SomeString> This is Second string </SomeString>"
The method should return a list of two strings as follows.(Note: these strings can be multi-lines)
"This is first string"
"This is Second string"

Thanks for your help in advance

Posted by: | Posted on: Oct 10, 2017

1 answers

Replies

2

Hi Jhon,
You can use following method to extract these strings in the form of a List of strings.

public List<string> GetListOfStringsBetweenTwoKeyWords(string source, string start, string end)
{
List<string> results = new List<string>();
string pattern = string.Format(
"{0}({1}){2}",
Regex.Escape(start),
".+?",
Regex.Escape(end));
foreach (Match m in Regex.Matches(source, pattern, RegexOptions.Singleline))// RegexOptions.Singleline | RegexOptions.Multiline
{
results.Add(m.Groups[1].Value);
}
return results;
}

And you call this method in the following way to get your desired result.

string sourceString = "<SomeString> This is first string </SomeString><SomeString> This is Second string </SomeString>";
List<string> results = GetListOfStringsBetweenTwoKeyWords(sourceString, "<SomeString>", "</SomeString>");

Replied by: | Replied on: Oct 23, 2017



Reply
×

Code block Hyperlink bold Quotes block Upload Images

Preview