正则表达式,路径的特定单词除外
Regex with exception of specific word of path
我需要用虚拟图像 URL 替换图像 URL。我目前在排除具有 ignore
文件名的路径时遇到问题。
我已经成功实现了匹配这两条路径的正则表达式:
images/image-filename.png
和 ../images/image-filename.png
使用以下正则表达式:
..\/images\/(.*?)\.(?:png|jpg|jpeg|gif|png|svg)|images\/(.*?)\.(?:png|jpg|jpeg|gif|png|svg)
但是,我想排除文件名中包含 ignore
单词的任何路径,例如:
images/image-filename-ignore.png
谢谢!
这是一个使用否定前瞻断言 ignore
不会作为文件名的一部分出现的选项:
images\/(?!.*ignore.*\.[^.]+).*\.(?:png|jpg|jpeg|gif|png|svg)
但是,您也可以通过实际将无效文件名与 ignore
匹配,然后从逻辑上排除这些匹配来继续:
images\/.*ignore.*\.(?:png|jpg|jpeg|gif|png|svg)
我的猜测是您可能想要添加一个 i
标志和单词边界:
\/?images\/(?!.*\bignore\b)[^.]*\.(?:png|jpe?g|gif|svg|tiff|other_extensions)
If you wish to explore/simplify/modify the expression, it's been
explained on the top right panel of
regex101.com. If you'd like, you
can also watch in this
link, how it would match
against some sample inputs.
我需要用虚拟图像 URL 替换图像 URL。我目前在排除具有 ignore
文件名的路径时遇到问题。
我已经成功实现了匹配这两条路径的正则表达式:
images/image-filename.png
和 ../images/image-filename.png
使用以下正则表达式:
..\/images\/(.*?)\.(?:png|jpg|jpeg|gif|png|svg)|images\/(.*?)\.(?:png|jpg|jpeg|gif|png|svg)
但是,我想排除文件名中包含 ignore
单词的任何路径,例如:
images/image-filename-ignore.png
谢谢!
这是一个使用否定前瞻断言 ignore
不会作为文件名的一部分出现的选项:
images\/(?!.*ignore.*\.[^.]+).*\.(?:png|jpg|jpeg|gif|png|svg)
但是,您也可以通过实际将无效文件名与 ignore
匹配,然后从逻辑上排除这些匹配来继续:
images\/.*ignore.*\.(?:png|jpg|jpeg|gif|png|svg)
我的猜测是您可能想要添加一个 i
标志和单词边界:
\/?images\/(?!.*\bignore\b)[^.]*\.(?:png|jpe?g|gif|svg|tiff|other_extensions)
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.