Parsing CSS by regex

前端 未结 8 1778
时光说笑
时光说笑 2020-11-27 17:37

I\'m creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can\'t get it to

8条回答
  •  被撕碎了的回忆
    2020-11-27 18:25

    That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it.

    Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g.,

    /([^{])\s*\{\s*([^}]*?)\s*}/
    

    Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }'s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it's probably even better to avoid regex's altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.

提交回复
热议问题