如何检查RegEx是否具有正确的语法?

Ele*_*ios 3 .net regex vb.net

我想知道在RegEx类中是否存在任何方法来检查表达式是否具有有效语法.

我不是说正则表达式匹配字符串或类似的东西,那么"IsMatch"或"Success"方法对我没有帮助.

要理解我,例如在使用RegEx.Match带有此表达式的方法时,它会抛出异常,因为表达式的语法无效:

"\\\" 
Run Code Online (Sandbox Code Playgroud)

(没有双引号)

我检查了正则表达式类方法,但我找不到任何像"tryparser".

然后检查表达式是否具有有效的语法我正在这样做:

Try
    Regex.Match(String.Empty, "\")
    Return True
Catch
    Return False
End Try
Run Code Online (Sandbox Code Playgroud)

只是我想知道我是否可以通过直接从regex类中的方法返回值或将regex类方法的结果转换为boolean 来简化代码.

更新:

我在执行时创建了RegEx,对我的外部工具没有帮助.

在此输入图像描述

xan*_*tos 5

从技术上讲,你可以使用正则表达式的构造函数...

Private Shared Function IsRegexValid(str As String) As Boolean
    Dim result As Boolean
    Try
        Dim rx as Regex = New Regex(str)
        result = True
    Catch ex As ArgumentException
        result = False
    End Try
    Return result
End Function
Run Code Online (Sandbox Code Playgroud)

或者构建Regex对象或返回的方法Nothing......

Private Shared Function TryBuildRegex(str As String) As Regex
    Dim result As Regex
    Try
        result = New Regex(str)
    Catch ex As ArgumentException
        result = Nothing
    End Try
    Return result
End Function
Run Code Online (Sandbox Code Playgroud)

然后

Dim isvalid As Boolean = IsRegexValid("\")
Run Code Online (Sandbox Code Playgroud)

要么

Dim rx As Regex = TryBuildRegex("\")

If rx IsNot Nothing Then
End If
Run Code Online (Sandbox Code Playgroud)