我想弄明白,如何在字符串中只允许单一类型的标记。例如,如果字符串 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
任何指南、建议或示例都会有所帮助
最佳答案
希望我正确理解了您的问题。您可以使用以下内容。
[^\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, ':');
关于c# - 字符串中只允许单一类型的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349656/