方法: 文字列から無効な文字を削除する

次の例では、静的 Regex.Replace メソッドを使用して、文字列から無効な文字を削除します。

Warning

信頼されていない入力で System.Text.RegularExpressions を無制限に使用すると、アプリケーションが サービス拒否攻撃の対象になる可能性があります。 信頼されていない入力で.NET正規表現を安全に使用する方法については、.NETの正規表現のベスト プラクティスを参照してください。

Example

この例で定義されている 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\.@-] は、単語文字、ピリオド、@ 記号、またはハイフン以外の文字と一致します。 単語文字は、任意の文字、10 進数字、またはアンダースコアなどの句読点コネクタです。 このパターンに一致するすべての文字は、置換パターンによって定義された文字列である String.Emptyに置き換えられます。 ユーザー入力で追加の文字を許可するには、正規表現パターンの文字クラスにそれらの文字を追加します。 たとえば、正規表現パターン [^\w\.@-\\%] では、入力文字列のパーセント記号と円記号も使用できます。

こちらも参照ください