
Question:
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 <a href="http://sizzlejs.com/" rel="nofollow">sizzle.js</a> 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!!
Answer1:The <a href="http://www.w3.org/TR/css3-selectors" rel="nofollow">Specification of CSS 3 Selectors</a> has a section about the <a href="http://www.w3.org/TR/css3-selectors/#w3cselgrammar" rel="nofollow">grammar of selectors</a> that you can use to build the regular expression. Just start with <em>selector</em> and replace each variable with its production until there are no variables left.
Answer2:Regular expressions don't make great <em>parsers</em>. (They may make great <em>parts</em> of a parser.) If you really need to do it, you'll probably need to actually use a parser. The <a href="https://stackoverflow.com/questions/512720/is-there-a-css-parser-for-c" rel="nofollow">answers to this question here</a> on StackOverflow may help there.