Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 仅允许字符串中的单个标记类型_C#_Regex_String_Linq - Fatal编程技术网

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, ':');