不正な文字を削除する正規表現を探しています。しかし、どのキャラクターが登場するかはわかりません。
例えば:
プロセスで、文字列を一致させたい([a-zA-Z0-9/-]*)
. したがって、上記の正規表現に一致しないすべての文字を置き換えたいと思います。
不正な文字を削除する正規表現を探しています。しかし、どのキャラクターが登場するかはわかりません。
例えば:
プロセスで、文字列を一致させたい([a-zA-Z0-9/-]*)
. したがって、上記の正規表現に一致しないすべての文字を置き換えたいと思います。
Kobiの回答のおかげで、受け入れられない文字を削除するヘルパー メソッドを作成しました。
許可されたパターンは正規表現形式である必要があります。角かっこで囲まれていることを期待してください。関数は、角かっこを開いた後にチルダを挿入します。有効な文字セットを記述するすべての正規表現で機能するとは限りませんが、使用している比較的単純なセットでは機能します。
/// <summary>
/// Replaces not expected characters.
/// </summary>
/// <param name="text"> The text.</param>
/// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>
/// <param name="replacement"> The replacement.</param>
/// <returns></returns>
/// // https://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
//https://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net
//[^ ] at the start of a character class negates it - it matches characters not in the class.
//Replace/Remove characters that do not match the Regular Expression
static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )
{
allowedPattern = allowedPattern.StripBrackets( "[", "]" );
//[^ ] at the start of a character class negates it - it matches characters not in the class.
var result = Regex.Replace(text, @"[^" + allowedPattern + "]", replacement);
return result; //returns result free of negated chars
}