語言
| Property | Value |
|---|---|
| 規則識別碼 | CA2028 |
| Title | 避免在 Regex.Match 之前重複呼叫 Regex.IsMatch |
| Category | 可靠性 |
| 修正是破壞性或非破壞性 | Non-breaking |
| 預設啟用於 .NET 10 版本 | No |
| 在 .NET 11 中預設啟用 | 作為建議 |
| 適用語言 | C# 與 Visual Basic |
Cause
程式碼呼叫 IsMatch,然後以相同的輸入和模式呼叫 Match。
規則描述
Regex.IsMatch 和 Regex.Match 都會評估正則表達式。 只要呼叫 Regex.Match 一次,確認傳回的 Group.Success 屬性,就能避免重複評估。
如何修正違規
用一個 Regex.IsMatch 呼叫取代 Regex.Match 呼叫。 使用 Match.Success 檢查輸入是否符合模式。
Examples
以下程式碼顯示違反 CA2028 規定:
if (Regex.IsMatch(input, pattern))
return Regex.Match(input, pattern).Value;
If Regex.IsMatch(input, pattern) Then
Return Regex.Match(input, pattern).Value
End If
只呼叫一次 Regex.Match:
var match = Regex.Match(input, pattern);
return match.Success ? match.Value : string.Empty;
Dim match = Regex.Match(input, pattern)
Return If(match.Success, match.Value, String.Empty)
隱藏警告的時機
只有當您有意重複評估同一正則表達式時,才抑制該警告。
隱藏警告
若要抑制單一違規,請在來源檔案中新增預處理器指令,以停用並重新啟用該規則。
#pragma warning disable CA2028
// The code that's violating the rule is on this line.
#pragma warning restore CA2028
若要停用檔案、資料夾或項目的規則,請在none中將其嚴重性設定為。
[*.{cs,vb}]
dotnet_diagnostic.CA2028.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告。