1

I'm writing a VBA function to evaluate whether a String is a Valid Full Name or not. For example:

  • Válid Full Name:

David Gilmour

Juan Munoz

Claudio Alberto da Silva

  • Invalid Full Name:

David Gilm01ur Jr.

Juan Muñoz

Cláudio Alberto da Silva

So the code of my function is this:

Function isVálidoNome(ByVal Texto As String) As Boolean
isVálidoNome = False
'
Dim strPattern As String: strPattern = "(^[a-zA-Z]+(\s?[a-zA-Z])*)*"
'Dim strPattern As String: strPattern = "\d"
Dim regularExpressions As New RegExp
'
regularExpressions.Pattern = strPattern
regularExpressions.Global = True
'
If (regularExpressions.Test(Texto)) Then
    isVálidoNome = True
End If


End Function

The pattern I used (^[a-zA-Z]+(\s?[a-zA-Z])*)* works fine in an app I used to test it (RegexPal), but when I run the code in VBA, Strings with digits, accents returns true

Why this problem or Did I make any mistake?

Community
  • 1
  • 1
tdmsoares
  • 533
  • 7
  • 24

1 Answers1

2

You need to use

^[a-zA-Z]+(?:\s[a-zA-Z]+)*$

See the regex demo

Set regularExpressions.Global = False.

Details:

  • ^ - start of string
  • [a-zA-Z]+ - 1 or more ASCII letters
  • (?: - start of a non-capturing group matching zero or more (*) sequences of:
    • \s - a single whitespace (add + after it to match 1 or more whitespaces)
    • [a-zA-Z]+
  • )* - end of the non-capturing group
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Man, it worked... But I'm still realizing: When I need a Regex expression depending of another, I have to use `(?:`, was this the cause of the problem, right? – tdmsoares Jun 05 '17 at 14:01
  • 1
    `(?:...)` is just a *non*-capturing group. It is the same as a capturing one (`(...)`), but does not create `.Submatches`. Just makes the inner structure of the Match object cleaner. – Wiktor Stribiżew Jun 05 '17 at 14:05
  • Excuse for my question, but what is the difference between a capturing group and a non-capturing group? I read about it, but I'm still puzzled – tdmsoares Jun 05 '17 at 14:27
  • 1
    It is explained well [here](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-a-question-mark-followed-by-a-colon). – Wiktor Stribiżew Jun 05 '17 at 14:31
  • And the Global option, what is it for? – tdmsoares Jun 05 '17 at 14:57
  • 1
    Global option is necessary to *extract* several matches from a single string. You are *validating*, you match the *whole string* against a single pattern. Hence, using Global option makes no sense. – Wiktor Stribiżew Jun 05 '17 at 15:34