如何将字符串与格式进行比较? vb.net

时间:2016-03-02 11:36:27

标签: vb.net

我有一个像这样的字符串" CP23332200-01"

我分裂了我的字符串,我得到了最后5个字符:" 00-01"那样:

Dim result As String = PartNo

                'for content parts
                If PartNo.Contains("CP") Then

                    If PartNo.Length > 5 Then
                        result = PartNo.Substring(PartNo.Length - 5)
                    End If



                End If

结果=" 00-01"

我如何将这个字符串与这样的格式进行比较:" int" - " int" 两个数字和两个数字 我想向你保证字符串" 00-01"总是那种格式。 注意*结果并非总是" 00-01"但格式总是两个数字 - 和两个数字

4 个答案:

答案 0 :(得分:2)

您可以使用RegEx

Imports System.Text.RegularExpressions

'Create one regex obj
Dim regex as new Regex("^[0-9]{2}-[0-9]{2}$")
'...

If PartNo.Contains("CP") Then
    If PartNo.Length > 5 Then
         result = PartNo.Substring(PartNo.Length - 5)
    End If

    'RegEx match against result
    If regex.IsMatch(result) Then 
        LBL_ERR.Text = "asdas"
    Else
        Exit Sub
    End If
End If

说明:

^ =字符串开头

[0-9] =仅允许数字

{2} =准确的两位数

$ =字符串结尾

我用一些数字检查了它,但你应该验证正则表达式here

答案 1 :(得分:1)

如果您不想要正则表达式,那么这也应该有效:

If PartNo.Contains("CP") Then

   If PartNo.Length > 5 Then
       result = PartNo.Substring(PartNo.Length - 5)
   End If
dim result as boolean = CheckForNumeric(result)
   If result = true then 
     LBL_ERR.Text = "asdas"
   Else
     Exit Sub
   End If
End If



Private Function CheckForNumeric(ByVal result as string) As Boolean
If result.Contains('-') Then
           Dim parts As String() = result.Split(New Char() {"-"c})
           If IsNumeric(parts(0)) and IsNumeric(parts(1))
               return true   
           End if
End if
return false
End Function

或更清晰的版本:

class Worker(models.Model):
    ip = models.GenericIPAddressField()
    created_date = models.DateTimeField()
    last_update = models.DateTimeField()

    #  but it's not the way I wish it was done:
    #  user = models.ForeignKey(User)

答案 2 :(得分:1)

您也可以使用Like运算符使用Pattern Matching

答案 3 :(得分:0)

                If PartNo.Contains("CP") Then

                    If PartNo.Length > 5 Then
                        result = PartNo.Substring(PartNo.Length - 5)
                    End If

                    If result Like "##-##" Then
                        LBL_ERR.Text = "asdas"
                    Else
                        Exit Sub
                    End If


                End If

我的问题的结果是: "#"替换一个字符