Home > Software design >  How would I match `.scss`, `.sass`, `.css` but not `.ass`? (RegExp)
How would I match `.scss`, `.sass`, `.css` but not `.ass`? (RegExp)

Time:03-03

I have the following regex: /\.([s]?[ac]ss)$/. The problem is, it matches .scss, .sass, .css, .ass. How would I make it not match .ass?

CodePudding user response:

Also this will match .scss, .sass and .css only, it is very readable and self-explanatory

/\.(sc|sa|c)ss$/

CodePudding user response:

You can use

\.(?!a)(s?[ac]ss)$

See the enter image description here

CodePudding user response:

In your pattern \.([s]?[ac]ss)$ you match .ass because the leading s optional and the character class [ac] can match both characters.

Instead you could use lookarounds assertions, or use an alternation | to allow only certain alternatives.

Some other variations could be:

\.(s?c|sa)ss$
  • \.Match a .
  • ( Capture group 1
    • s?c|sa Match an optional s then match c or match sa
  • ) Close group 1
  • ss$ Match ss at the end of the string

Regex demo

\.(s[ac]|c)ss$

A variation on the previous pattern, now matching sa or sc or c

Regex demo

If in your environment the lookbehind assertion is supported:

\.s?[ac]ss$(?<!\.ass)
  • \.s? Match a . and optional s
  • [ac] Match either a or c
  • ss$ Match ss at the end of the string
  • (?<!\.ass) Negative lookbehind, assert not .ass to the left

Regex demo

Note that if you want a match only, you can also use a non capture group (?:...) instead.

  • Related