简体   繁体   中英

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!

(?!.*:)(?:[.#]\\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM