1

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!!

Robin Maben
  • 19,662
  • 16
  • 61
  • 93
  • 1
    Technically, I don't think there are any invalid selectors, just some that don't select anything. At any rate, tasks such as brace matching and handling different contexts (normal, inside square brackets, inside quotes) are very regex-unfriendly, and typically done with a parser of some sort. – Tgr Nov 16 '10 at 07:45
  • 1
    @Jonathan: From his code snippet, I'm guessing he wants to do this in C#. – T.J. Crowder Nov 16 '10 at 07:48
  • @T.J. the snippet looks somewhat generic, but yeah, you're probably right – Jonathan Day Nov 16 '10 at 07:49
  • @Jonathan: Well, that *plus* the tag. ;-) – T.J. Crowder Nov 16 '10 at 07:50
  • @Tgr - But there are invalid classnames (e.g. starts with numeric) so, by extension, a selector that matches an invalid classname could be considered invalid? Ref http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names/449005#449005 – Jonathan Day Nov 16 '10 at 07:56
  • You can build the regular expression right from the [grammar of selectors](http://www.w3.org/TR/css3-selectors/#w3cselgrammar). – Gumbo Nov 16 '10 at 08:07
  • @TJ, Jonathan: I included the c# tag, assuming somebody, somewhere might already have this in their helper library or somethin.. Or atleast know about something relevant. – Robin Maben Nov 16 '10 at 08:08
  • 1
    @Jonathan Day: sorry I wasn't clear, I was talking about jQuery selctors, not CSS. `.123` is a jQuery selector that selects the (invalid) class `123` (try it in your browser of choice, it actually works). Whether that makes the jQuery selector itself invalid is up to debate. Also, jQuery's selector language is very open, you can easily add your own operators, or even change what `.` means. – Tgr Nov 18 '10 at 07:40

2 Answers2

1

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.

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
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.

Gumbo
  • 594,236
  • 102
  • 740
  • 814