Regular Expression for valid css and/or jQuery sel

2019-08-03 19:06发布

问题:

I need something like this :

Regex validSelector = new Regex("^[.#a-zA-Z0-9_:[] ]+[,><a-zA-Z0-9_~=\"\":[] ]*$");

Has anybody written a regular expression for validating jQuery or CSS selectors? (CSS3/jQuery1.4)

Or, does anybody know where I can find a regex or regex generator to validate a jQuery selector?(or atleast CSS selectors?)

I've tried going through the code of sizzle.js bu John Resig and the w3c docs for css (http://www.w3.org/Style/CSS/) but ended up havin a headache :(

Thought i'd rather ask if any of you has already written or used some snippet for this.

Thanks!!

回答1:

The Specification of CSS 3 Selectors has a section about the grammar of selectors that you can use to build the regular expression. Just start with selector and replace each variable with its production until there are no variables left.



回答2:

Regular expressions don't make great parsers. (They may make great parts of a parser.) If you really need to do it, you'll probably need to actually use a parser. The answers to this question here on StackOverflow may help there.