简体   繁体   中英

String split c# but ignore some cases

I am trying to split some txt file according to one string. In another words, text file includes many "COMPONENT" word and I want to split the text depend on the "COMPONENT" word.

Here is my code:

string[] splitComponents(string a)
{
    return a.Split(new String[] { "COMPONENT" }, StringSplitOptions.None);
}

It is working well but it detects some cases for example " COMPONENT_ " and split the text also which is not proper in my case. How can I ignore this situation? I only want to split "COMPONENT" word not "COMPONENT_". Thank you in advance.

You could do a regex split on the pattern COMPONENT(?!_) :

string[] splitComponents(string a)
{
    return Regex.Split(a, @"COMPONENT(?!_)");
}

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