Try a similar technique:
string example = "abc,,def,,123"; // richTextBox2.Text
string[] result = Regex.Split( example, @"(?<=[^,]),,(?=[^,])" );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
In richTextBox2 TextChanged I'm highlighting specific chars/strings in the richTextBox in this case the chars are ,,
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
if ((richTextBox2.Text != "" && textBoxRootDirectory.Text != "" &&
Directory.Exists(textBoxRootDirectory.Text)) || richTextBox2.Text != "")
{
startButton.Enabled = true;
Properties.Settings.Default["Setting2"] = richTextBox2.Text;
Properties.Settings.Default.Save();
}
else
{
startButton.Enabled = false;
}
if (IsColouring) return;
IsColouring = true;
try
{
if (richTextBox2.Text.Length > 0)
{
Highlight(richTextBox2);
}
}
finally
{
IsColouring = false;
}
}
And the Highlight method :
void Highlight(RichTextBox richTextBox)
{
const int WM_SETREDRAW = 0x000B;
SendMessage(richTextBox.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
var sel_start = richTextBox.SelectionStart;
var sel_len = richTextBox.SelectionLength;
richTextBox.SelectAll();
richTextBox.SelectionColor = Color.Black;
for (int y = 0; y < richTextBox.Lines.Length; y++)
{
string s = richTextBox.Lines[y];
int x = richTextBox.GetFirstCharIndexFromLine(y);
foreach (Match m in Regex.Matches(s, @"(?<=[^,])(?<sep>,,)(?=[^,])"))
{
richTextBox.SelectionStart = x + m.Groups["sep"].Index;
richTextBox.SelectionLength = 2;
richTextBox.SelectionColor = Color.Red;
}
}
richTextBox.SelectionStart = sel_start;
richTextBox.SelectionLength = sel_len;
SendMessage(richTextBox.Handle, WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
richTextBox.Invalidate();
}
[DllImport("user32")]
private extern static IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
And last in a Start button click event I split this chars ,, from the richTextBox2 :
private void startButton_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
wordsSplitValues = richTextBox2.Text.Split(new string[] { ",," }, StringSplitOptions.None);
SetWorkerMode(true);
backgroundWorker1.RunWorkerAsync();
}
}
The problem is that the line :
wordsSplitValues = richTextBox2.Text.Split(new string[] { ",," }, StringSplitOptions.None);
Get array of all the places with the chars ,, even if they are in black color or any color.
I want to split only the places that the chars ,, are in red.
So in the end in the array(maybe it's better to change it to a List<string>) will contain the text between all the red chars ,,
The way it's working now I'm getting items in the array that are empty because some of the text in the richTextBox2 is also ,,,,,,, in black.
Try a similar technique:
string example = "abc,,def,,123"; // richTextBox2.Text
string[] result = Regex.Split( example, @"(?<=[^,]),,(?=[^,])" );