2

I'm trying to match all the CSS selectors and directives below excluding any comments and any media queries.

a {color: red !important;}

#p1 {
        margin-top: 20px !important
      }

/* Client-specific styles */

      .ExternalClass,  
      .ExternalClass p,  
      .ExternalClass span,  
      .ExternalClass font,  
      .ExternalClass td,  
      .ExternalClass div {
        line-height: 100%;
      }

a {}

@media query {
    a { display:none }  
}

I've come up with the following RegEx: [a-zA-Z#.:*]{1}[^\/*]+?{[\s\S]*?}. This matches everything correctly but includes the @media query. I've tried using a negative lookahead e.g. (?!.+@media.+) but that didn't help.

What can I do to extract only the selectors/directives?

Example: https://regex101.com/r/JmjthP/3

Solution

With help from @Wiktor Stribiżew the working solution was this:

/^(?!.*@media)[\t ]*([a-zA-Z#.:*\[][^{\/]*\s*){[\s\S]*?}/

3
  • 1
    Try regex101.com/r/JmjthP/4 Commented Sep 25, 2018 at 18:49
  • Thanks a lot. I made a few tweaks and it's working great. Do you want to post that as an answer and I'll accept it? Commented Sep 26, 2018 at 15:34
  • Ok, posted with an explantion. Commented Sep 26, 2018 at 15:50

1 Answer 1

2

You may use

^(?!.*@media) *[a-zA-Z#.:*][^{]*{[\s\S]*?}

See the regex demo

Details

  • ^ - start of string
  • (?!.*@media) - no @media allowed after any 0+ chars other than line break chars
  • * - 0+ spaces
  • [a-zA-Z#.:*] - a letter, #, ., : or *
  • [^{]* - zero or more chars other than {
  • { - a { char
  • [\s\S]*? - 0+ chars, as few as possible.
  • } - a } char
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.