Skip to main content
 首页 » 编程设计

c#之使用替换时正则表达式删除空格

2024年02月01日28sxdcgaq8080

我的情况不是删除空白,而是保留它们。我有这个字符串 >[database values] 我想找到它。我创建了这个 RegEx 以找到它,然后进入并删除 >、[、]。下面的代码采用来自文档的字符串。第一个模式寻找任何被 >[some stuff] 包围的东西然后进入并“删除”>, [, ]

  string decoded = "document in string format"; 
  string pattern = @">\[[A-z, /, \s]*\]"; 
  string pattern2 = @"[>, \[, \]]";  
  Regex rgx = new Regex(pattern); 
  Regex rgx2 = new Regex(pattern2);          
  foreach (Match match in rgx.Matches(decoded)) 
  {                      
    string replacedValue= rgx2.Replace(match.Value, ""); 
    Console.WriteLine(match.Value); 
    Console.WriteLine(replacedValue); 

我首先在 Console.WriteLine 中得到的是正确的。所以我会得到像 >[123 sesame St] 这样的东西。但是我的第二个输出显示我的替换不仅删除了字符,还删除了空格,所以我会得到类似这样的内容 123sesameSt。我在我的 Regex 中没有看到任何空格被替换。我是不是忘记了什么,也许它隐含在替换中?

请您参考如下方法:

您的模式中的 [A-z,/,\s] 和 [>,\[,\]] 也在寻找逗号和空格。只列出字符而不分隔它们,像这样:[A-Za-z/\s]

string pattern = @">\[[A-Za-z/\s]*\]"; 
string pattern2 = @"[>,\[\]]"; 

编辑以包含 Casimir 的提示。