Example:

.class01 { .class02 { color:#000; } } 

What are the options for analyzers of this example. It comes to mind only with the help of regulars from the bottom up.
The use of ready-made libraries do not offer. The ultimate goal is to create a tree like the one below.

 [{ name: '.class01', data: '', links: [{ name: '.class02', data: 'color:#000;', links: [] }] }] 
  • Translating into Computer Science: from the line with the source code on LESS, you want to make an abstract syntax tree in which you can select section selectors, their immediate properties and nested sections. Seem to be? - D-side
  • Look for articles about syntax parsers. Often comes across ANTLR - a tool for generating structured text parsers. Even if it is not needed, there are still chances to get acquainted with the theory of this case - Sergey
  • LESS is selected as an example. @ D-side Yes, it seems. - Oleg
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Step 1. We perform lexical analysis , breaking the source text into tokens . Get an array like:

 '.class01', '{', '.class02', '{', 'color', ':', '#000', ';', '}', '}' 

Step 2. We perform the syntax analysis , making up a hierarchical structure based on the resulting array. In this example, the opening brace is the beginning of the content block, and the closing, respectively, its end. Thus, the structure will look like this:

 var tree = { '.class01': { '.class02': { color: '#000' } } }; 

Step 3. On the basis of the data obtained, we compose a structure for our needs.

PS To build the structure of the source text, you can forget about using regular expressions , since it is difficult to keep track of the pair of opening / closing brackets in them.

  • Thanks for the information. But how to follow the pairing from the bottom up, with the help of regulars, I can see approximately. And from the top down I understand the regulars will not allow. Example. We find the deepest attachment, memorize it into an array, and in the text we replace it with @N (where N is the number in the array), etc. The second step is to analyze replacing text links with the real one - Oleg
  • @ user2245887 Well, here’s a simple example: .class1:before { content: '{{{{{}}}}}}}' } which delivers unnecessary trouble when using regular expressions for this purpose. - edem