Regular expression learning (1): Vue template analysis

Regular expression learning (1): Vue template analysis

Vue uses regular expressions when parsing the Template. The most complicated one is the analysis of attributes. This article mainly reviews the knowledge points that are easily overlooked in the regularities through the regularization of static attributes and dynamic attributes.


The following is the analysis of static properties in Vue source code.

The length of the expression is very long, and it will be a headache at first, but you can see that there are many parentheses in the expression, it seems that the parentheses divide the expression into several parts.


In regular expressions, parentheses () indicate the meaning of capture. For string types, there is match. The match method returns an array of classes. The object contains a capture group, which means that the content wrapped by () can be captured.

For example: in the picture below, match is used to return a class array, the first digit is the matched result, and the second digit e is the captured content.

Back to attribute, first divide the regular into three parts through ()

first part

^\s*: * means 0 or more,/s is a space symbol, and ^ means a character beginning with the content following ^, then the attribute can be a string that starts with a space

the second part


Single match: []

Match only one character, the character satisfies the content in []

Not: [^]

Match a character, see if the character does not meet the content in [^]

Escape symbol:/

For characters with special meaning in regular expressions, you need to use the/symbol to escape.

([^\s"'<>/=]+): Capture non-blank characters, non-", non-', non-<, non->, non-/, non-= characters with a length of at least 1

the third part

(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+ )))?

Match but not capture:?:

For example: Although the e in () meets the conditions, there is no'e' in the result returned by match


literal meaning

3.1 Capture the equal sign

:\s*(=)\s*: there can be spaces before and after the equal sign

3.2 The writing of the first attribute value

"([^"]*)"+, there is at least one value in the form of "value", capture value

3.3 The writing of the second attribute value

'([^']*)'+, at least one value in the form of'value', capture value

3.4 The third type of attribute value writing

([^\s"'=<>`]+), capture non-spaces, non-", non-', non-=, non-<, non->, non-` symbol length is at least 1 string

Test case


Here is a brief analysis:

\w: [A-Za-z0-9_]

(?:v-[\w-]+:|@|:|#) matches v-string: or @ or: or #


Capture [] wrapped non=string


([^\s"'=<> ]+) ' = < > The length of the symbol is at least 1 string

Test case