简体   繁体   中英

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 ">" .

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");

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM