正则表达式捕获不包含字符串并以扩展名结尾的文本 [英] Regex to catch text not containing a string and ending with an extension

查看:22
本文介绍了正则表达式捕获不包含字符串并以扩展名结尾的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 2 个正则表达式,一个包含关键"并以(s)css"结尾的捕获字符串,第二个用于不包含关键"的字符串(具有相同的扩展规则).

I'm trying to have 2 regex, one catching string containing 'critrical' and ending with '(s)css' and second one for string which don't contain 'critical' (with the same extentions rule).

我已经有了第一个,它是 /.*?critical.*\.s?css$/

I already have the first one and it is /.*?critical.*\.s?css$/

但我无法制作第二个.我认为它会像 /.*?(?<!\.critical).*\.s?css$/ 一样简单.但是,似乎没那么容易,因为它不起作用......

But I can't manage to make the second one. I thought it would be as easy as /.*?(?<!\.critical).*\.s?css$/. But, seems it's not that easy as it doesn't work...

推荐答案

试试这个正则表达式(对于不包含关键词,最后包含 css 的字符串):

Try this regex(for the string not containing the word critical and containing css in the end):

^(?!.*critical).*s?css$

点击演示

说明:

  • ^ - 断言字符串的开始
  • (?!.*critical) - negative lookahead 验证字词 critical 不存在于字符串中
  • .* - 匹配 0+ 次(贪婪地)除新行之外的任何字符
  • s?css - 匹配可选的 s 后跟 css
  • $ - 断言字符串的结尾
  • ^ - asserts the start of the string
  • (?!.*critical) - negative lookahead to validate that the word critical is not present in the string
  • .* - matches 0+ occurrences(greedily) of any character except a new line
  • s?css - matches an optional s followed by css
  • $ - asserts the end of the string

并且,对于包含单词critical和最后包含css的字符串,您可以尝试:

And, for the string containing the word critical and containing css in the end, you can try:

^(?=.*critical).*s?css$

点击演示

这个正则表达式的唯一区别是它使用正向前瞻来确保字符串critical存在于字符串中的某处.

The only difference with this regex is that it uses a Positive lookahead to make sure that the string critical exist somewhere in the string.

这篇关于正则表达式捕获不包含字符串并以扩展名结尾的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆