如何:從字串中刪除無效的字元How to: Strip Invalid Characters from a String

下列範例會使用靜態 Regex.Replace 方法,從字串中去除無效的字元。The following example uses the static Regex.Replace method to strip invalid characters from a string.

範例Example

您可以使用此範例中定義的 CleanInput 方法,去除使用者在文字欄位中可能已輸入的有害字元。You can use the CleanInput method defined in this example to strip potentially harmful characters that have been entered into a text field that accepts user input. 在此情況下,CleanInput 會去除句點 (.)、符號 (@) 以及連字號 (-) 以外的所有非英數字元,並傳回剩餘的字串。In this case, CleanInput strips out all nonalphanumeric characters except periods (.), at symbols (@), and hyphens (-), and returns the remaining string. 不過,您可以修改規則運算式模式,讓它去除輸入字串中不應包含的任何字元。However, you can modify the regular expression pattern so that it strips out any characters that should not be included in an input string.

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\.@-] 會比對任何非文字字元的字元、句號、@ 符號或連字號。The regular expression pattern [^\w\.@-] matches any character that is not a word character, a period, an @ symbol, or a hyphen. 文字字元是指任何字母、十進位數字或底線這類標點符號連接子。A word character is any letter, decimal digit, or punctuation connector such as an underscore. 任何符合這個模式的字元都會使用 String.Empty (這是由取代模式所定義的字串) 來取代。Any character that matches this pattern is replaced by String.Empty, which is the string defined by the replacement pattern. 若要允許使用者輸入其他字元,可將這些字元新增至規則運算式模式中的字元類別。To allow additional characters in user input, add those characters to the character class in the regular expression pattern. 例如,規則運算式模式 [^\w\.@-\\%] 也允許在輸入字串中使用百分比符號與反斜線。For example, the regular expression pattern [^\w\.@-\\%] also allows a percentage symbol and a backslash in an input string.

另請參閱See also