0

Trying to post-process some CSS here and need a regex to select data-attribute selectors in CSS.

It will need to select the following selectors (just the selector but in it's entirety):

[data-attr] {
 // some css
}

.cool-class[data-another-attr] {
 // some css
}

#id[data-one-more-attr] {
 //  some css
}

So that would select [data-attr], .cool-class[data-another-attr] and #id[data-one-more-attr].

What I have so far (not even close):

/(\[data-*)\w/g

Thanks in advance for your help, RegEx always stumps me.

Dave Lunny
  • 750
  • 8
  • 21
  • Do you need only the name of `data` attribute or all the style properties in it – Tushar Jul 21 '15 at 15:04
  • 1
    Might be a bit too loose, but this will get you started I guess: `/([.+]?\[data\-(.+)\])/g`: http://regexr.com/3be7m – Bjorn Jul 21 '15 at 15:05

1 Answers1

3

You can use following regex

((#|\.)?[\w-]+)?(\[data(-\w+)+\])/g

Explanation:

  1. (#|\.)?: Matches # or . literal optionally
  2. [\w-]+: Matches any alphanumeric character with - any number of times
  3. ((#|\.)?[\w-]+)?: Matches CSS id or class selector optionally(?)
  4. (\[data(-\w+)+\]): Matches data attribute

Demo

RegEx101 Demo

Tushar
  • 85,780
  • 21
  • 159
  • 179