Javascript regex to define CSS code inside a string?

Possible duplicates:
CSS parsing in JavaScript / jQuery
CSS parsing with RegEx in JavaScript

How do I know if a string contains CSS rules?

Examples of rules:

selector { property:value; } selector { property:value; } selector{property:value} ... 

Basically, I want to find out if a text block represents PHP + HTML or CSS code.

One way to do this is to think of trimming the text and then matching the first character of the text with # or a CSS selector like body , p , etc. You think this is a good idea?

+4
source share
2 answers

TL; DR; Consider using the right CSS parser, such as JSCSSP , for a final check.

It depends on the purpose, and the regex can be completely invalid.

If this is just an โ€œattemptโ€ to see if it can โ€œcontainโ€ CSS selectors, then I might be inclined to match too broadly, leading to a crash in something complicating CSS string values โ€‹โ€‹(like โ€œ}โ€) or there are CSS comments, and will accept a wide range of input, which is invalid CSS:

 (?:\s*\S+\s*{[^}]*})+ // use anchored 

Similarly, an expression that should detect the simplest HTML (but invalid) with tags and only bad CSS cases (matches in comments or CSS lines or crazy child selectors):

 <(?:br|p)[^>{]*>|</\w+\s*> // use case-insensitive 

Happy coding.

Also see: CSS parsing in JavaScript / jQuery

+3
source

http://arxiv.org/abs/1106.4064 may interest you.

Algorithmic Programming Language Identification

David Klein, Kyle Murray, Simon Weber

(Presented on June 21, 2011 (v1), last modified on November 9, 2011 (this version, version 2))

Motivated by the amount of code that is not identifiable on the Internet, we present a practical method of algorithmic identification of the source code programming language. Our work is based on supervised learning and intelligent statistical functions. We also studied, but abandoned the grammatical approach. During testing, our implementation significantly exceeds the existing system, which relies on the Bayesian classifier. The code is written in Python and is available under the MIT license.

+2
source

Source: https://habr.com/ru/post/1392134/


All Articles