我试图弄清楚,如何在字符串中只允许单一类型的标记。例如,如果字符串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任何指南、建议或示例都会有所帮助
1 回答
慕工程0101907
TA贡献1887条经验 获得超5个赞
我希望我正确理解了你的问题。你可以使用以下。
[^\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, ':');
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报
0/150
提交
取消
