C# 用包含括号的字符串替换字符串的问题
我当前遇到与regex.replace相关的问题。我在checkedlistbox中有一个项目,它包含一个带括号“()”的字符串: 所选项目内的示例设置为C# 用包含括号的字符串替换字符串的问题,c#,regex,replace,checkedlistbox,C#,Regex,Replace,Checkedlistbox,我当前遇到与regex.replace相关的问题。我在checkedlistbox中有一个项目,它包含一个带括号“()”的字符串: 所选项目内的示例设置为 hello how are you (today) 我在正则表达式中使用它,如下所示: if (e.NewValue == CheckState.Checked) { //replaces the string without parenthesis with the one with parenthesis //ex:&l
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() + ">");
}
if(e.NewValue==CheckState.Checked)
{
//将不带括号的字符串替换为带括号的字符串
//喂,你好(今天)(工作得很好)
richTextBox1.Text=regx2[selected]。替换(richTextBox1.Text,“->”+checkedListBox1.Items[selected].ToString());
}
else if(e.NewValue==CheckState.Unchecked)
{
//将带括号的字符串替换为不带括号的字符串
//你好,你好(今天)-->(问题)
richTextBox1.Text=regx2[4]。替换(richTextBox1.Text,“”);
}
它可以在第一个条件下替换字符串,但无法在第二个条件下再次替换设置,因为它有括号“()”,您知道如何解决此问题吗??
响应的thx:)要在正则表达式中使用任何特殊字符作为文本,需要使用反斜杠对其进行转义。如果要匹配
1+1=2
,正确的正则表达式是1\+1=2
。否则,加号具有特殊含义
特殊字符:
- 反斜杠\
- 插入符号^
- 美元符号$
- 句号或圆点
- 竖条或管道符号|
- 问号
- 星号或星号*
- 加号+
- 左括号(,
- 右括号)
- 开口方括号[,
- 开放式花括号{
regx2[4] = new Regex("->" + checkedListBox1.SelectedItem.ToString().Replace("(", @"\(").Replace(")", @"\)"));
但我只会使用string.replace()
,因为您没有进行任何解析。我无法告诉您正在从/转换到什么,以及为什么在if
中使用selected
作为正则表达式数组的索引,在else
中使用4作为索引,而不是:
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
尝试:
string.Replace对于你想要做的事情来说应该是好的,因为你可以将代码缩短到只包含相关部分。不需要搞乱GUI,例如Btw,你能给出一些关于上述问题的例子吗?你能给出一些例子吗?我已经试过了,但仍然无法改变设置。。
regx2[4] = new Regex( "->" + checkedListBox1.SelectedItem.ToString());
regx2[4] = new Regex(Regex.Escape("->" + checkedListBox1.SelectedItem));