Search code examples
phpregexstring

Explain the Regular Expression /^[a-zA-Z ]*/


I understand that the regex pattern must match a string which starts with the combination and the repetition of the following characters:

  1. a-z
  2. A-Z
  3. a white-space character

And there is no limitation to how the string may end!


First Case

So a string such as uoiui897868 (any string that only starts with space, a-z or A-Z) matches the pattern... (Sure it does)

Second Case

But the problem is a string like 76868678jugghjiuh (any string that only starts with a character other than space, a-z or A-Z) matches too! This should not happen!


I have checked using the php function preg_match() too , which returns true (i.e. the pattern matches the string). Also have used other online tools like regex101 or regexr.com. The string does match the pattern. Can anybody could help me understand why the pattern matches the string described in the second case?


Solution

  • Your regex is completely useless: it will trivially match any string (empty, non-empty, with numbers, without,...), regardless of its structure.

    This because

    • with ^, you enforce the begin of the string, now every string has a start.
    • You use a group [A-Za-z ], but you use a * operator, so 0 or more repititions. Thus even if the string does not contain (or begins with) a character from [A-Za-z ], the matcher will simply say: zero matches and parse the remaining of the string.

    You need to use + instead of * to enforce "at least one character".