/^[a-zA-Z]+$/
vs
/[^a-zA-Z]+$/
The ^
at the start of the expression means "Anchor at the beginning of the string".
The ^
inside the character class []
expression means negate
.
So /^[a-zA-Z]$/
matches a string that consists entirely (from beginning to end) of upper case and lower case alphabetic characters, while /[^a-zA-Z]$/
matches the "end of the string that does not consist of alphabetic characters" (for example, numbers at the end of the string).
this is a string -- matches neither
(contains non alphabetic, but doesn't end in it)
this is a number: 123 -- second expression matches ': 123'
(string ends in non-alphabetic characters)
this -- first expression matches 'this'
(string contains only alphabetic characters)
In case 1 the ^
indicates the beginning of the input. Case two negates the term.
Case 1: From beginning(^
) to end ($
) match a-zA-Z
0 or more(+
) times
Case 2: Match everything that does not(^
) end($
) with a-zA-Z
0-x(+
) chars
/^[a-zA-Z]+$/
means that the string should
^
: start with
[a-zA-Z]
: lower case or upper case alpha character
+
: At least one of the previous, in this case at least one of alpha character
$
: Should end with a uppper case or lower case alpha character
Exmaple:
OnLyUpPeRaNdLoWeRcAsEaNdNoSpAcEs
/[^a-zA-Z]+$/
[^a-zA-Z]
: NOT an upper case or lower case character
+
: At least one of the previous, in this case at least one character but NOT of upper case or lower case alpha character
$
: Should end with a none
upper case or lower case alpha character
Example:
123456789
anything12345 <-- this works because we didn't specify how the string should start but we know that it should end with a non alpha character