Search code examples
javascriptnode.jsstylelint

How to RegEx match double underscore, but not single ( __ not _)


I'm working on a stylelint rule for modified BEM, which is essentially saying that a single underscore is not allowed, but a double underscore is.

match case:

  • foo__bar

non-match cases:

  • foo_bar

  • foo_bar__baz

I would (ideally) like not just a working code snippet, but an explanation of how a problem like this is best solved using only JavaScript RegEx

Here are the relevant docs for stylelint: https://stylelint.io/user-guide/rules/selector-class-pattern/

Here is a test suite that would need to pass: https://regex101.com/r/NjwOa3/3/tests


Solution

  • You can try a regular expression like below.

    ^[^_]*_{2,2}[^_]*$
    

    or try this for matching only the double underscores.

    _{2,2}