【问题标题】:Allow only single type of mark in string字符串中只允许单一类型的标记
【发布时间】:2019-08-16 09:27:33
【问题描述】:

我试图弄清楚,如何在字符串中只允许单一类型的标记。例如,如果字符串inputStr 包含不同的标记:

string inputStr = "hello, how are you? ~ say something: what's up? hi... tell me. what?! ok: so,";

这样:

string outputStr = Regex.Replace(inputStr, @"[^\w\s]", "");

结果我会得到没有任何标记的outputStr

hello how are you say something whatsup hi tell me what ok so

想要得到想要的结果,我只想在outputStr 中保留单个特定冒号":" 标记:

hello how are you say something: whatsup hi tell me what ok: so

任何指南、建议或示例都会有所帮助

【问题讨论】:

    标签: c# regex string linq


    【解决方案1】:

    希望我正确理解了您的问题。您可以使用以下。

    [^\w\s:]
    

    代码

    string outputStr = Regex.Replace(inputStr, @"[^\w\s:]", "");
    

    如果你想拥有一个自定义函数,你可以执行以下操作,以便你可以重复使用不同字符的方法。

     public static string ExtendedReplace(string sourceString, char charToRetain)
     {
          return Regex.Replace(sourceString, $@"[^\w\s{charToRetain}]", "");
     }
    

    现在你可以使用如下。

    string inputStr = "hello, how are you? ~ say something: what's up? hi... tell me. what?! ok: so";
    string outputStr = ExtendedReplace(inputStr, ':');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多