C# 仅允许字符串中的单个标记类型
我试图弄明白,如何在字符串中只允许单个类型的标记。例如,如果字符串C# 仅允许字符串中的单个标记类型,c#,regex,string,linq,C#,Regex,String,Linq,我试图弄明白,如何在字符串中只允许单个类型的标记。例如,如果字符串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 ho
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 inputStr = "hello, how are you? ~ say something: what's up? hi... tell me. what?! ok: so";
string outputStr = ExtendedReplace(inputStr, ':');
代码
如果希望有一个自定义函数,可以执行以下操作,以便使用不同的字符重用该方法
public static string ExtendedReplace(string sourceString, char charToRetain)
{
return Regex.Replace(sourceString, $@"[^\w\s{charToRetain}]", "");
}
现在,您可以使用以下命令
[^\w\s:]
string inputStr = "hello, how are you? ~ say something: what's up? hi... tell me. what?! ok: so";
string outputStr = ExtendedReplace(inputStr, ':');