Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx don't match if starts with character?

I have this regex:

/(((\w+)|(\.\w+)|(\#\w+)|\*)(\[(.+(=".+"|\*".+"|\^".+"|))\])?(::|:)?)+(?=[ \S]*\{)/gm

Which I am trying to use to match CSS selectors. Consider this pseudo-code CSS input:

.main {
  property: value;
}

.one, .two a[href$=".com"] {
  .subclass {
    property: value;
  }
}

.test:before, .test:after:active {}

The pattern above will return the following matches:

['.body', '.one', '.two', 'a[href$=".com"]', '.subclass', '.test:before', '.test:after:active']

I am trying to modify the pattern so that psuedo selectors are not matched. So all the other matches should still be valid, but .test:before should just be .test and .test:after:active should also just match .test. I can't think of a way to do this without either a negative look-behind, or a way to not match if the first character is a :.

I'm implementing this in Node, and I don't want to lock my script to Node > 9.2.0 just to use negative look-behinds in my regex.

Any ideas would be greatly appreciated!

like image 555
topherlicious Avatar asked Nov 07 '22 14:11

topherlicious


1 Answers

(?!.*:)(?:[.#]\w+|\w+\[.*\])

You could use something like this?

This uses a negative lookahead to ensure it doesn't capture anything with a colon beside it, as well as using a simplified version of your matcher for psuedo css elements.

See it working here

like image 152
KyleFairns Avatar answered Nov 14 '22 23:11

KyleFairns