[英]Replacing a string with strings that include parenthesis issue
我目前遇到与regex.replace有关的问题。 我在清单框中有一个项目,其中包含带有括号“()”的字符串:
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
所选项目内的示例设置为
hello how are you (today)
我在正则表达式中使用它是这样的:
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() + ">");
}
它能够在第一个条件下替换字符串,但在第二个条件上却无法再次替换设置,因为它具有括号“()”,您知道如何解决此问题吗? 谢谢你的回应:)
要将任何特殊字符用作正则表达式中的文字,您需要使用反斜杠对其进行转义。 如果要匹配1+1=2
,则正确的正则表达式为1\\+1=2
。 否则,加号具有特殊含义。
http://www.regular-expressions.info/characters.html
特殊的角色:
要解决此问题 ,您可以执行以下操作:
regx2[4] = new Regex("->" + checkedListBox1.SelectedItem.ToString().Replace("(", @"\(").Replace(")", @"\)"));
但是我只使用string.replace()
因为您没有进行任何解析。 我不能告诉你从/到转化,为什么您使用selected
的作为指数的正则表达式阵列上if
和4作为索引else
。
代替:
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
尝试:
regx2[4] = new Regex(Regex.Escape("->" + checkedListBox1.SelectedItem));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.