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

标签 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 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/

相关文章:

c++ - 将一段文本读入字符串 vector

python - 从字符串中的字符生成像素矩阵

c# - 语言间的方法差异(Python->C#)

c# - 使用领域驱动设计时应用存储在数据库中的业务规则

c# - 如何在 C# 中使用 sendkeys 发送键盘组合 Shift+Win+LEFT?

regex - 匹配时如何使一个词优先于其他词?

java - String.ReplaceAll 中的正则表达式

c# - 通过 for 语句循环遍历 System.Collections.Generic.Dictionary

c# - 在 C# 中使用 Regex 提取 Form 标记中的操作属性?

php - 如何验证这种格式的字符串 : p[1 or more numbers]?