1

RESOLUTION - Provided By Wiktor - I have implemented this into my question.

Validating user input while they're typing to match the following format - 11A11

    Private Sub RegexFormatterExample(sender As Object, e As EventArgs)

    Dim txt As TextBox = sender
    Dim pattern As String = ""

    Select Case txt.Name
        Case "txt_example"
            pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$"
        Case Else
            pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$"
    End Select

    Dim strText As String = txt.Text

    While Not Regex.IsMatch(strText, pattern) AndAlso Not strText = ""
        strText = strText.Substring(0, strText.Length - 1)
    End While

    txt.Text = strText
    txt.Select(txt.Text.Length, 0)
End Sub

I have also attached a .TextChanged handler to the specified txtbox.

The provided answer only allows the user to type in the following format which is what I asked for.

What I want

Thanks Wiktor!

Edit

Further to this scenario there is a case where the user has the ability to enter only a minus symbol rather than passing an empty string for where they don't know the value.

To implement this I amended the RegEx pattern to the following. Regex Demo

I am not sure if this is the most efficient way but it seems to be working for me.

4
  • 2
    Like ^[A-Z]{2}[0-9][A-Z]{2}\z ? See demo Commented Mar 9, 2020 at 8:53
  • What is your Problem? Where is the fail. Provide more information. Commented Mar 9, 2020 at 8:56
  • btw: you dont need the {1} quantifier. [0-9]{2}[A-Z]{1}[0-9]{2}\z. == [0-9]{2}[A-Z][0-9]{2}\z Commented Mar 9, 2020 at 8:57
  • 1
    Try ^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$. See the regex demo Commented Mar 9, 2020 at 9:41

2 Answers 2

1

You may use

^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?\z

See the .NET regex demo online (\z is replaced with \r?$ since the demo is run against a single multiline string).

Details

  • ^ - start of string
  • \d{1,2} - one or two digits
  • (?: - start of a non-capturing group:
    • (?<=^\d{2}) - a positive lookbehind check: there must be two digits at the start of the string immediately to the left of the current position
    • [A-Z] - an uppercase letter
    • \d{0,2} - 0, 1 or 2 digits
  • )? - end of the non-capturing group, repeat 1 or 0 times (i.e. make it optional)
  • (?:[A-Z]\d{0,2})? - an optional sequence of an uppercase letter and then 0, 1 or 2 digits
  • \z - the very end of string (no \n is allowed at the end of the string).
Sign up to request clarification or add additional context in comments.

1 Comment

I have implemented this into my question, thankyou!
0

Maybe you can trim \n off (if any) and use

"^[0-9]{2}[A-Z][0-9]{2}$"

instead?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.