正则表达式匹配所有出现但忽略以”vendor”开头的情况。

huangapple go评论57阅读模式
英文:

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)] 表示任何不是以下字符之一的字符:(vendor)。这不会按您期望的工作。

为了匹配不以名为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/

regex101.com上尝试

为了限制整行只有两个级别,使用:

^             # 在行首,匹配一个字符串
(?!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/

regex101.com上尝试

英文:

[^(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.

huangapple
  • 本文由 发表于 2023年5月7日 11:23:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定