Search code examples
javascriptcssregexuncss

Regex for css data attribute selectors


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.


Solution

  • 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