【问题标题】:C# - Regex replace any character using dot . in bracket [ ]C# - 正则表达式使用点替换任何字符。在括号 [ ]
【发布时间】:2015-04-11 07:36:22
【问题描述】:

例子:

string str = "Example[1]";
string output = Regex.Replace(str, "[.]", "");

但它不起作用,输出仍然是:Example[1]

虽然结果只是“示例”?

请帮忙:(

【问题讨论】:

  • 你的预期输出是什么?
  • 我预计我的输出将是:示例
  • 你至少应该转义[,因为这样它只匹配一个.。请参阅:\\[.\\]

标签: c# regex replace


【解决方案1】:

您的方法是正确的.. 只需在括号中使用转义字符..

string output = Regex.Replace(str, @"\[.\]", "");

输出:示例

编辑:如果括号中有多个字符.. 使用"\[.+?\]"

【讨论】:

  • 我试过 .+ 但它不起作用,例如我有“ExampleOne[10] ExampleTwo[11]”,结果将是“ExampleOne”。 ExampleOne 之后的任何字符都将被删除。我预计结果将是“ExampleOne ExampleTwo”
  • ^ 是的,这是完美的! :D
【解决方案2】:

使用以下表达式:

string output = Regex.Replace(str, @"\[\d+\]", "");

它寻找符号[、任意位数和符号]

【讨论】:

  • 谢谢,我试试看:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多