HOW TO:從字串中刪除無效的字元

更新:2007 年 11 月

下列程式碼範例使用靜態 Regex.Replace 方法將字串中無效的字元刪除。您可以使用此處所定義的 CleanInput 方法,刪除輸入到表單中接受使用者輸入的文字欄位中之潛在危害字元。CleanInput 在刪除 @、- (破折號)、和 .(句號) 之外的非英數字元之後,會傳回字串。

範例

using System;
using System.Text.RegularExpressions;

public class Example
{
    static string CleanInput(string strIn)
    {
        // Replace invalid characters with empty strings.
        return Regex.Replace(strIn, @"[^\w\.@-]", ""); 
    }
}

請參閱

其他資源

.NET Framework 規則運算式