如何:從字串中刪除無效的字元

下列範例會使用靜態 Regex.Replace 方法,從字串中去除無效的字元。

警告

使用 System.Text.RegularExpressions 來處理不受信任的輸入時,請傳遞逾時。 惡意使用者可以提供輸入給 RegularExpressions,導致拒絕服務的攻擊。 使用 RegularExpressions 的 ASP.NET Core 架構 API 會傳遞逾時。

範例

您可以使用此範例中定義的 CleanInput 方法,去除使用者在文字欄位中可能已輸入的有害字元。 在此情況下,CleanInput 會去除句點 (.)、符號 (@) 以及連字號 (-) 以外的所有非英數字元,並傳回剩餘的字串。 不過,您可以修改規則運算式模式,讓它去除輸入字串中不應包含的任何字元。

using System;
using System.Text.RegularExpressions;

public class Example
{
    static string CleanInput(string strIn)
    {
        // Replace invalid characters with empty strings.
        try {
           return Regex.Replace(strIn, @"[^\w\.@-]", "",
                                RegexOptions.None, TimeSpan.FromSeconds(1.5));
        }
        // If we timeout when replacing invalid characters,
        // we should return Empty.
        catch (RegexMatchTimeoutException) {
           return String.Empty;
        }
    }
}
Imports System.Text.RegularExpressions

Module Example
    Function CleanInput(strIn As String) As String
        ' Replace invalid characters with empty strings.
        Try
            Return Regex.Replace(strIn, "[^\w\.@-]", "")
            ' If we timeout when replacing invalid characters, 
            ' we should return String.Empty.
        Catch e As RegexMatchTimeoutException
            Return String.Empty
        End Try
    End Function
End Module

規則運算式模式 [^\w\.@-] 會比對任何非文字字元的字元、句號、@ 符號或連字號。 文字字元是指任何字母、十進位數字或底線這類標點符號連接子。 任何符合這個模式的字元都會使用 String.Empty (這是由取代模式所定義的字串) 來取代。 若要允許使用者輸入其他字元,可將這些字元新增至規則運算式模式中的字元類別。 例如,規則運算式模式 [^\w\.@-\\%] 也允許在輸入字串中使用百分比符號與反斜線。

另請參閱