英文:
Regex to match all occurrences but ignore if it starts with vendor
问题
我试图编写一个正则表达式来匹配所有的 anystring/css/
,但是要排除 vendor/css/
,例如:
apples/css/
vendor/css/
kiwi/css/
Apple/css/
vendor/css/
应该匹配的是:
apples/css/
kiwi/css/
Apple/css/
我尝试了以下正则表达式,但它并没有正确工作,只忽略了第一个 vendor/css/
,而不是其他的:
\b[^(vendor)].+\/css\/
英文:
I'm trying to do a regex to match to find and match all anystring/css/
except vendor/css/
for example
apples/css/
vendor/css/
kiwi/css/
Apple/css/
vendor/css/
should match
apples/css/
kiwi/css/
Apple/css/
i was able to come up with but its not working correctly and only ignores the first vendor/css/
but not the others
\b[^(vendor)].+\/css\/
答案1
得分: 0
[^(vendor)]
表示任何不是以下字符之一的字符:(
、v
、e
、n
、d
、o
、r
、)
。这不会按您期望的工作。
为了匹配不以名为vendor
的文件夹开头的目录(?),请使用负向先行断言:
\b # 匹配词边界,然后
(?!vendor\/) # 不以 'vendor/' 开头,
.+ # 任何不包含
\/css\/ # 后跟 '/css/'。
这会匹配:
apples/css/
kiwi/css/
Apple/css/
endor/css/
venv/css/
foo/bar/css/
lorem/css/ipsum/css/
dolor/sit/amet/vendor/css/
vendors/css/
baz/css/qux
但不会匹配:
vendor/css/
为了限制整行只有两个级别,使用:
^ # 在行首,匹配一个字符串
(?!vendor\/) # 不是 'vendor/',
[^\/]+\/ # 由1个或多个非斜杠杠字符,然后是斜杠杠,
css\/ # 后跟 'css/'
$ # 紧挨着行尾。
这会匹配:
apples/css/
kiwi/css/
Apple/css/
endor/css/
venv/css/
vendors/css/
但不会匹配:
foo/bar/css/
lorem/css/ipsum/css/
dolor/sit/amet/vendor/css/
baz/css/qux
vendor/css/
英文:
[^(vendor)]
means any character that is not one of (
, v
, e
, n
, d
, o
, r
, )
. This wouldn't work as you expected.
To match directories (?) that doesn't start with a folder named vendor
, use negative lookahead:
\b # Match a word boundary, then
(?!vendor\/) # start with 'vendor/',
.+ # anything that does not
\/css\/ # followed by '/css/'.
This matches:
apples/css/
kiwi/css/
Apple/css/
endor/css/
venv/css/
foo/bar/css/
lorem/css/ipsum/css/
dolor/sit/amet/vendor/css/
vendors/css/
baz/css/qux
...but not:
vendor/css/
Try it on regex101.com.
To limit the whole line to two levels, use:
^ # At the beginning of line, match a string that
(?!vendor\/) # is not 'vendor/',
[^\/]+\/ # and consists of 1+ non-slash characters, then a slash,
css\/ # followed by 'css/'
$ # right before the end of line.
This matches:
apples/css/
kiwi/css/
Apple/css/
endor/css/
venv/css/
vendors/css/
...but not:
foo/bar/css/
lorem/css/ipsum/css/
dolor/sit/amet/vendor/css/
baz/css/qux
vendor/css/
Try it on regex101.com.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论