简体   繁体   中英

C# split string by multiple characters

I want to split a string like this:

"---hello--- hello ------- hello --- bye"

into an array like this:

"hello" ; "hello ------- hello" ; "bye"

I tried it with this command:

test.Split(new string[] {"---"}, StringSplitOptions.RemoveEmptyEntries);

But that doesn't work, it splits the "-------" into 3 this "---- hello".

Edit:

I can't modify the text, it is an input and I don't know how it looks like before I have to modify it.

An other example would be:

--- example ---

--------- example text --------

--- example 2 ---

and it should only split the ones with 3 hyphens not the one with more.

You can use a Regex split. The regex uses a negative lookahead (?!-) to only match three - exactly. See also Get exact match of the word using Regex in C# .

string sentence = "---hello--- hello ------- hello --- bye";
var result = Regex.Split(sentence, @"(?<!-)---(?!-)");
foreach (string value in result) {
   Console.WriteLine(value.Trim());
}

.net Fiddle

Solution to find your Tokens with regex:

(?<!-)---(?!-)

Console.WriteLine(String.Join(",", System.Text.RegularExpressions.Regex.Split("---hello--- hello ------- hello --- bye", "(?<!-)---(?!-)")))

I suggest trying Regex.Split instead of string.Split :

  string source = "---hello1--- hello2 ------- hello3 --- bye";

  var result = Regex
    .Split(source, @"(?<=[^-]|^)-{3}(?=[^-]|$)") // splitter is three "-" only
    .Where(item => !string.IsNullOrEmpty(item))  // Removing Empty Entries
    .ToArray();

  Console.Write(string.Join(";", result));

Outcome:

  hello1; hello2 ------- hello3 ; bye
  1. Replace ----- by something else that is never is your test, like @@@ test.replace("------", "@@@")
  2. Split your string
  3. Replace @@@ by ------

I would suggest using an neutral character like "/split" or something like that. Than you can use test.Split(...) without woriing that it split something else that you want. Your code would now look something like that:

string test = "hello\split hello ------- hello \split bye";
test.Split("\split", StringSplitOptions.RemoveEmptyEntries);

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