Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 494
  • Last Modified:

How to validate a comma delimited string with Regex

How to use RegEx to validate a string in the format of

12C;325252C;99999C;378C;28C;3535345342C;1C;56896745C

The valid format would be any number of numerical value + "C;" as the delimiter except the last element ends with "C"

Thanks.
0
cyn_jiang
Asked:
cyn_jiang
1 Solution
 
Bob LearnedCommented:
1) That looks like semi-colon delimited text, and not comma-delimited

2) Try this:

Imports System.Text.RegularExpressions

    If ValidateInput("12C;325252C;99999C;378C;28C;3535345342C;1C;56896745C") Then
      MessageBox.Show("Valid")
    End If

  End Sub

  Private Function ValidateInput(ByVal input As String) As Boolean
    Dim pattern As String = "^\d*C$"

    Dim elements As String() = input.Split(";")

    For Each element As String In elements

      If Not Regex.IsMatch(element, pattern) Then
        MessageBox.Show("Element is invalid:  " & element)
        Return False
      End If

    Next element

    Return True

  End Function

Bob
0
 
Fernando SotoCommented:
Hi cyn_jiang;

This sample code will do what you want.

Imports System.Text.RegularExpressions

        ' Sample Data
        Dim data As String = "12C;325252C;99999C;378C;28C;3535345342C;1C;56896745C"
        ' Regex pattern to validate data
        Dim pattern As String = "^(\d+C;|\d+C)+$"

        ' Check to see if data is valid
        If Regex.IsMatch(data, pattern) Then
            MessageBox.Show("The data is vaild")
        End If


Fernando
0
 
cyn_jiangAuthor Commented:
Sorry, it is semi-colon delimited text, I would allow them to input space in between the elements.

So I modified Fernando's code a little bit.

Imports System.Text.RegularExpressions
 
Dim pattern as String = "^(\d+(C; *)|\d+C)+$"

      If Regex.IsMatch(data, pattern) Then
            MessageBox.Show("The data is vaild")
        End If

Thanks for your help.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now