亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字符串中只允許單一類型的標記

字符串中只允許單一類型的標記

C#
九州編程 2022-11-13 14:19:29
我試圖弄清楚,如何在字符串中只允許單一類型的標記。例如,如果字符串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, ':');


查看完整回答
反對 回復 2022-11-13
  • 1 回答
  • 0 關注
  • 99 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號