語言
以下範例使用靜態 Regex.Replace 方法從字串中剔除無效字元。
Warning
若在不受信任的輸入下不受限制地使用, System.Text.RegularExpressions 應用程式可能會遭受 阻斷服務攻擊。 請參閱 .NET 中正則表達式的最佳實務,以獲得如何在不受信任輸入下安全使用 .NET 正規表達式的指引。
Example
你可以使用本範例中定義的 CleanInput 方法,從接受使用者輸入的文字欄位中移除已輸入的可能有害字元。 在此情況下,CleanInput 會移除所有非英數字元,但句點(.)、at 符號(@)和連字號(-)除外,並傳回剩餘的字串。 不過,你可以修改正則表達式模式,將其剔除不該包含在輸入字串中的字元。
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\.@-\\%] 模式也允許在輸入字串中加入百分比符號和反斜線。