字符串中只允许单一类型的标记

我试图弄清楚,如何在字符串中只允许单一类型的标记。例如,如果字符串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

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


九州编程
浏览 140回答 1
1回答

慕工程0101907

我希望我正确理解了你的问题。你可以使用以下。[^\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, ':');
打开App,查看更多内容
随时随地看视频慕课网APP