Reputation: 181
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.
Upvotes: 1
Views: 1282
Reputation: 1455
Solution to find your Tokens with regex:
(?<!-)---(?!-)
Console.WriteLine(String.Join(",", System.Text.RegularExpressions.Regex.Split("---hello--- hello ------- hello --- bye", "(?<!-)---(?!-)")))
Upvotes: 4
Reputation: 9463
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());
}
Upvotes: 6
Reputation: 186688
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
Upvotes: 3
Reputation: 11
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);
Upvotes: 0
Reputation: 878
test.replace("------", "@@@")
Upvotes: 2