我試圖弄清楚,如何在字符串中只允許單一類型的標記。例如,如果字符串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 關注
- 99 瀏覽
添加回答
舉報
0/150
提交
取消