Andrew Kilburn
Andrew Kilburn

Reputation: 41

What code will help me check a string for at least 2 numericals characters?

Basically, I am trying to create a random password generator using VB. However I am stumped at one certain place. I do not know how to check the string to see if at least 2 numerical characters have been inserted. I thought maybe a contain would help but I can only check for one character. Can anyone help me? The code at the moment is placed below:

        Dim sChars As String="qwertyuiopasdfghjklzxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ1234567890"
        Dim sPassword As String = ""
        Dim iLength As Integer
        Do Until iLength >= 10 And sPassword.Contains(???)
        Loop

Upvotes: 0

Views: 128

Answers (3)

Fabian Bigler
Fabian Bigler

Reputation: 10895

A little faster version than the regex approach:

    Dim password As String = "somePasswordToTest24hehe6"
    Dim numberCounter As Integer
    Dim counterLimit As Integer = 2
    Dim hasValidCountOfNumbers As Boolean
    For Each ch As Char In password
        If Char.IsDigit(ch) Then
           numberCounter += 1
        End If
        If numberCounter >= counterLimit Then
           hasValidCountOfNumbers = True
           Exit For
        End If
   Next

   If hasValidCountOfNumbers Then
                'do probably nothing
   Else
                'notify that password validation failed
   End If

Upvotes: 0

user4365195
user4365195

Reputation:

You can use the following scenario

    Dim sChars As String = "qwertyuiopasdfghjklzxcvbnmMNBV1CXZLKJHGFDSAPOIUYTREWQ"
    Dim output As String = New String((From c As Char In sChars Select c Where Char.IsDigit(c)).ToArray())
    If output.Length >= 2 Then
        MsgBox("success")
    Else
        MsgBox("Doesn't meet the requirement") ' for this input this message will displayed
    End If

suppose the input will be

Dim sChars As String="qwertyuiopasdfghjklzxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ1234567890" then it will display Success

Upvotes: 2

Kaustav Banerjee
Kaustav Banerjee

Reputation: 285

You can use the below code for matching the regex expressions:

Imports System.Text.RegularExpressions

Module Module1
    Sub Main()
    Dim regex As Regex = New Regex("\d{2}")
    Dim match As Match = regex.Match("Dot 77 Perls")
    If match.Success Then
        Console.WriteLine(match.Value)
    End If
    End Sub
End Module

This will match for two numerical occurrences in the string and return the result. You can use the regex match in your web/console application and not execute the entire module

Upvotes: 1

Related Questions