将VB函数转换为Regex?

时间:2016-11-07 02:52:58

标签: regex vb.net

我有这个功能来检查用户输入的字符串的验证(仅限15位数字)。我可以做到这一点,因为我是RegEx的新手。

^[1-9]{1}\d{14}$

这是我在VB中的功能。

    Public Function IsNPWPValid(ByVal _npwp9 As String, Optional ByVal emptyAllowed As Boolean = False) As Boolean
    Try
        _npwp9 = RemoveFormatNpwp(_npwp9).Trim
        If _npwp9.Length < 9 Or IsNumeric(_npwp9) = False Then
            Return False
        Else
            If emptyAllowed And Left(_npwp9, 9) = "000000000" Then
                Return True
            End If
            If Left(_npwp9, 3) = "240" Then
                Return True
            Else
                Dim n1, n2, n3, n4, n5, n6, n7, n8, n9 As Integer

                n1 = CInt(_npwp9.Substring(0, 1))
                n2 = CInt(_npwp9.Substring(1, 1)) * 2
                n3 = CInt(_npwp9.Substring(2, 1))
                n4 = CInt(_npwp9.Substring(3, 1)) * 2
                n5 = CInt(_npwp9.Substring(4, 1))
                n6 = CInt(_npwp9.Substring(5, 1)) * 2
                n7 = CInt(_npwp9.Substring(6, 1))
                n8 = CInt(_npwp9.Substring(7, 1)) * 2

                If n2 > 9 Then
                    n2 -= 9
                End If
                If n4 > 9 Then
                    n4 -= 9
                End If
                If n6 > 9 Then
                    n6 -= 9
                End If
                If n8 > 9 Then
                    n8 -= 9
                End If
                n9 = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8
                While n9 > 10
                    n9 -= 10
                End While
                n9 = 10 - n9

                If n9 <> _npwp9.Substring(8, 1) Then
                    Return False
                Else
                    Return True
                End If
            End If
        End If
    Catch ex As Exception
        ShowError(ex)
    End Try
End Function

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

这是您应该使用的:

Dim regex As Regex = New Regex("^[1-9]{1}\d{14}$")
return regex.IsMatch(_npwp9)