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.

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.