RegEx do not match if starts with character?

I have this regex:

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

What I'm trying to use to match CSS selectors. Consider this CSS pseudo-code input:

 .main { property: value; } .one, .two a[href$=".com"] { .subclass { property: value; } } .test:before, .test:after:active {} 

In the above template, the following matches will be returned:

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

I am trying to change the pattern so that psuedo selectors are not matched. So all other matches must be valid, but .test:before should just be .test and .test:after:active should also just match .test . I cannot think of a way to do this without a negative appearance or a way to not match if the first character is :

I implement this in Node, and I don't want to block my script until Node> 9.2.0 in order to use negative images in my regex.

Any ideas would be greatly appreciated!

+5
source share
1 answer

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

Can you use something like this?

This uses a negative result to ensure that it does not capture anything with a colon next to it, and also uses a simplified version of your helper for psuedo css elements.

See how it works here

+1
source

Source: https://habr.com/ru/post/1273475/


All Articles