elo_win
elo_win

Reputation: 23

Check if string is uppercase and numbers

I want to check if a string contains only uppercase letters and numbers. I have attempted to solve this using RegExp and what I have so far is:

Function CheckForInvalidChars()
    dim b
    Set re = New RegExp
    re.Pattern = "[A-Z_0-9]"    
    b = re.Test("eS")
    msgbox b
End Function

However the variable "b" returns true since I guess it finds a match in the "S" although I want that particular string to return false since not all letters are uppercase. How would I go about achieving this?

I have tried to do this with functions as well using IsNumeric but can't find a IsUpperCase.

Upvotes: 2

Views: 2800

Answers (4)

Gerardo Lima
Gerardo Lima

Reputation: 6712

@Andris is right, correct the regular expression as follows:

Function CheckForInvalidChars()
    dim b
    Set re = New RegExp
    re.Pattern = "^[A-Z_0-9]*$"
    b = re.Test("eS")
    msgbox b
End Function

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

I'd recommend to just UCase the string if you want to enforce uppercase letters. Then you can simplify the check to this:

Function CheckForInvalidChars(s)
  Set re = New RegExp
  re.Pattern = "^\w+$"
  CheckForInvalidChars = re.Test(s)
End Function

teststring = InputBox("Input something")
teststring = UCase(teststring)

WScript.Echo "" & CheckForInvalidChars(teststring)

The escape sequence \w matches word characters, i.e. uppercase letters, lowercase letters (ruled out due to the prior UCase), digits, and underscores. The + rules out empty strings by requiring at least one word character.

Upvotes: 1

Andris Leduskrasts
Andris Leduskrasts

Reputation: 1230

Generally speaking, if you want to match whole string using regex, you will usually end up using ^ and $ to describe the start and end of string.

Also, just [A-Z_0-9] matches a single character.

Assuming you don't allow whitespaces, ^[A-Z_0-9]*$ would be the regex you're looking for.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234865

If UCase(s) <> s then there is at least one lower case letter in the string s.

Upvotes: 3

Related Questions