Search code examples
c#regexreplacecheckedlistbox

Replacing a string with strings that include parenthesis issue


i am currenty having a problem related with regex.replace . I have an item in checkedlistbox that contains a string with parenthesis "()" :

regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());

the example setence inside the selected item is

hello how are you (today)

i use it in regex like this :

if (e.NewValue == CheckState.Checked)
{
    //replaces the string without parenthesis with the one with parenthesis
    //ex:<reason1> ----> hello, how are you (today) (worked fine)
    richTextBox1.Text = regx2[selected].Replace(richTextBox1.Text,"->"+checkedListBox1.Items[selected].ToString());
}
else if (e.NewValue == CheckState.Unchecked)
{
    //replaces the string with parenthesis with the one without parenthesis
    //hello, how are you (today)----><reason1> (problem)
    richTextBox1.Text = regx2[4].Replace(richTextBox1.Text, "<reason" + (selected + 1).ToString() + ">");
}

it is able to replace the string on the first condition but unable to re-replace the setences again on second because it has parenthesis "()", do you know how to solve this problem?? thx for the response :)


Solution

  • Instead of:

    regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
    

    Try:

    regx2[4] = new Regex(Regex.Escape("->" + checkedListBox1.SelectedItem));