首页 > 解决方案 > 正则表达式检测具有 .png 且介于 [ 和 ] 之间的字符串

问题描述

我正在寻找一种正则表达式模式,它可以检测 [ 和 ] 之间的任何字符串并在其中包含 .png 。例如 [任何与 .png 匹配的内容] 到目前为止,我有这个:“\[[^>]+]”,它检测 [ 和 ] 之间的任何内容,但我只想包含具有 .png 的字符串

我对正则表达式没有经验。

如果我通过“abc [abc.png] abc [abc] abc”我想得到 [abc.png]

如果我通过 "abc [abc.pngabc] abc [abc] abc" 我想得到 [abc.pngabc]

标签: regex

解决方案


如果您只想要括号之间以 .png 结尾的字符串,请尝试以下操作:(假设您的字符串始终以“.png]”结尾)

//this will find a string of any length that ends with .png and is surrounded by []
(?<=\[)\S*\.png(?=\])
\\(?<=...) is called a positive lookbehind and checks if something is adjacent to the left of your match
\\(?=...)Positive lookbehind checks for something to the right

如果您还想包含 [] ,请使用:(这使用非方括号字符,因为它假定它们是您的字符串中唯一不能包含或分隔字符串的内容。完全健壮。

\[[^\]\[]*\.png[^\]\[]*\]

例子。

[abc.png] abc [abc] [hey.png]
\\will return
[abc.png] [hey.png]

推荐阅读