简体   繁体   中英

How to remove all strings with brackets in C#?

string data = "DisplayName=[s9dFSQ]Height=[rPBM7]User=[5cY]Date=[KJn7Zzd1f]";

How can I remove all values in the brackets?

I am planning to use something like

string result="";
string[] wholestring = data.Split('[');
foreach (string f in wholestring)
{
     result += f.Split("]")[0];
}
result.Replace('[','').Replace(']','');

//result would be: DisplayName=Height=User=Date=

I would appreciate if you could show a more proper way.

Assuming that all brackets are paired up correctly and there is no nesting, you could use Regex.Replace :

var withoutBrackets = Regex.Replace(withBrackets, @"\[[^\]]*\]" , "");

Demo.

If you need your regex to work with nested brackets as well, see this Q&A for an in-depth explanation of how this can be done in .NET.

Here you go:

static void Main()
{
    string data = "DisplayName=[s9dFSQ]Height=[rPBM7]User=[5cY]Date=[KJn7Zzd1f]";

    Console.WriteLine(RemoveBracketsContent(data)); // prints DisplayName=Height=User=Date=
}

static string RemoveBracketsContent(string data)
{
    string result = string.Empty;
    bool brackedStarted = false;

    for (int i = 0; i < data.Length; i++)
    {
        if (data[i].Equals('['))
        {
            brackedStarted = true;
            continue;
        }
        else if (data[i].Equals(']'))
        {
            brackedStarted = false;
            continue;
        }

        if (brackedStarted)
        {
            continue;
        }

        result += data[i];
    }

    return result;
}

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