regular matching results are different. There is no reason why. You said that you added parentheses, you should understand the meaning of parentheses: group the matching results
begins with ^
and ends with $
has higher priority than |
, so the first example is actually |
two separate segments ^ ([a-zA-Z] + [A-Za-z0-9 -] * [a-zA-Z0-9])
and ([a-zA-Z]) $
.
you can write down this priority
\
(), (?:), (?=), []
*, +, ?, {n}, {n,}, {n,m}
^, $, \ :
| ""
Let me join in the fun:
Let's first take a look at
/ ^ ([a-zA-Z] + [A-Za-z0-9 -] * [a-zA-Z0-9]) | ([a-zA-Z]) $/
the meaning of the regular expression
below is the regular railway diagram
group -sharp1group -sharp2
"11a" group -sharp2
/^(([a-zA-Z]+[A-Za-z0-9-]*[a-zA-Z0-9])|([a-zA-Z]))$/
group -sharp1group -sharp1
group -sharp1
group -sharp2 group -sharp3 group -sharp2 group -sharp3
group -sharp2 "[1-] ||[0-] |[1]"
group -sharp3 "[1]"
group -sharp2 "11a" group2 , group -sharp3a
.
but group-sharp3 only hits the last trailing character, not the first character 1, so the whole match is not matched.
I don't know if this answer is clear enough.
Let me give a simple and rude explanation.
the first indicates that it begins with (group1) or ends with (group2), and the second represents
that begins with (group1) or begins with (group2).
Please take a look at the following case:
D:\temp>node test.js
1 true true
2 true true
12 true false
10 true false
02 true false
you can see that reg1
represents the entire string starts with 1
or ends with 2
, and reg2
indicates that the entire string can only be 1 or 2. It can be understood as |
has lower priority than $
and ^
.