Why is this an issue?
Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if
they are given a regular expression that does not conform to that syntax.
To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to
capturing groups should use the correctly spelled name or number of the group.
Negative lookahead and negative lookbehind groups cannot be combined with RegexOptions.NonBacktracking
. Such combination would throw
an exception during runtime.
Noncompliant code example
Public Sub DoSomething(Input As String)
Dim Rx As New Regex("[A") ' Noncompliant
Dim Match = Regex.Match(Input, "[A") ' Noncompliant
Dim Matches = Regex.Matches(Input, "[A") ' Noncompliant
Dim Replace = Regex.Replace(Input, "[A", "replacement") ' Noncompliant
Dim Split = Regex.Split(Input, "[A") ' Noncompliant
If (Regex.IsMatch(Input, "[A")) Then ' Noncompliant
End If
Dim NegativeLookahead As New Regex("a(?!b)", RegexOptions.NonBacktracking) ' Noncompliant
Dim NegativeLookbehind As New Regex("(?<!a)b", RegexOptions.NonBacktracking) ' Noncompliant
End Sub
Compliant solution
Public Sub DoSomething(Input As String)
Dim Rx As New Regex("[A-Z]")
Dim Match = Regex.Match(Input, "[A-Z]")
Dim Matches = Regex.Matches(Input, "[A-Z]")
Dim Replace = Regex.Replace(Input, "[A-Z]", "replacement")
Dim Split = Regex.Split(Input, "[A-Z]")
If (Regex.IsMatch(Input, "[A-Z]")) Then
End If
Dim NegativeLookahead As New Regex("a(?!b)")
Dim NegativeLookbehind As New Regex("(?<!a)b")
End Sub