admin 管理员组文章数量: 1184232
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?
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?
6 Answers
Reset to default 11Also this will match .scss, .sass and .css only, it is very readable and self-explanatory
/\.(sc|sa|c)ss$/
Another way using alternation:
\.((?:s[ac]|c)ss)$
RegEx Demo
Here this non-capturing group (?:s[ac]|c) will match sa or sc or just c.
How about just
/\.(s?css|sass)$/
Regex doesn't need to be very complex to work. This is a lot easier to read for other programmers (i.e. you in about 3 months) and does the same.
Sure you can smush it more together, but why would you? Regex are complicated enough, keep 'm simple if you can :)
Demo
You can use
\.(?!a)(s?[ac]ss)$
See the regex demo. Details:
\.- a dot(?!a)- the next char cannot bea(s?[ac]ss)- Group 1: an optionals,aorcand thenss$- end of string.
Another regex that can work is
\.(s(?:css|ass)|css)$
See this regex demo. Details:
\.- a dot(s(?:css|ass)|css)-sand thencssorassorcss$- end of string.
NOTE: if you have a dynamic, user-defined list of such fixed strings to match after a . at the end of string, you can build these regexes automatically using the code at the bottom of my answer.
You could just list the ones you want to match:
let rx = /\.css|\.sass|\.scss/; // alphabetized for future maintenance
This isn't fancy, but it is very clear and easy to add more later.
I tested it here :
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 1s?c|saMatch an optionalsthen matchcor matchsa
)Close group 1ss$Matchssat 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 optionals[ac]Match eitheraorcss$Matchssat the end of the string(?<!\.ass)Negative lookbehind, assert not.assto the left
Regex demo
Note that if you want a match only, you can also use a non capture group (?:...) instead.
本文标签: javascriptHow would I match scss sass css but not ass (RegExp)Stack Overflow
版权声明:本文标题:javascript - How would I match `.scss`, `.sass`, `.css` but not `.ass`? (RegExp) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1739476784a2059481.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论