Instead of:
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
Try:
regx2[4] = new Regex(Regex.Escape("->" + checkedListBox1.SelectedItem));
سؤال
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 :)
المحلول
Instead of:
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
Try:
regx2[4] = new Regex(Regex.Escape("->" + checkedListBox1.SelectedItem));
نصائح أخرى
To use any of the special characters as a literal in a regex, you need to escape them with a backslash. If you want to match 1+1=2
, the correct regex is 1\+1=2
. Otherwise, the plus sign has a special meaning.
http://www.regular-expressions.info/characters.html
special characters:
To fix it you could probably do this:
regx2[4] = new Regex("->" + checkedListBox1.SelectedItem.ToString().Replace("(", @"\(").Replace(")", @"\)"));
But I would just use string.replace()
since you aren't doing any parsing. I can't tell what you're transforming from/to and why you use selected
as an index on the regex array in the if
and 4 as the index in the else
.