2016-11-07 73 views
-1

我有這個功能來檢查用戶輸入字符串的驗證(僅15位數字)。因爲我是RegEx的新手,所以我可以做到這一點。將VB函數轉換爲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 

任何幫助將不勝感激。謝謝。

+0

您有公式,以便您有解決方案。也許你可以檢查['Regex.IsMatch'](https://msdn.microsoft.com/en-us/library/3y21t6y4(v = vs.110).aspx)來實現你的解決方案。 – Prisoner

回答

0

這是你應該使用什麼:

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

'return regex.IsMatch(_npwp9)' –

+0

你是對的。我編輯了我的答案 – Hadi