Harshal Bhamare
Harshal Bhamare

Reputation: 53

How to remove string between two string including both start string as well end string?

Example string :

"< harshal bhamare > sfjkgdbgfbguifg < fbgfg >";

I want to remove total string "< harshal bhamare >" which is starts with "<" and ends with ">".

Upvotes: 0

Views: 65

Answers (2)

Richard
Richard

Reputation: 850

If you didn't want to use the regex solution you could simply iterate over each character and watch for start/end characters, omitting those within.

StringBuilder sb = new StringBuilder();
bool skip = false;
foreach (char c in "< harshal bhamare > sfjkgdbgfbguifg < fbgfg >")
{
    if (c.Equals('<')) skip = true;
    if (c.Equals('>')) { skip = false; continue; }

    if (!skip) sb.Append(c);

}

System.Console.WriteLine(sb.ToString());

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can use a regular expression for that:

<.*?>(.*)<.*?>

It removes everything inside the brackets including the brackets itself (the ? makes it non-greedy, so < and > inside the text block is allowed), and captures the text in between. You can get that out by getting the first capture, like in this C# code:

string output = Regex.Replace(input, @"<.*>(.*)<.*>", "$1");

Upvotes: 3

Related Questions