javascript 正则表达式在同一行上有多个匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10516458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:07:52  来源:igfitidea点击:

Regex multiple matches on same line

javascriptregex

提问by Phill Duffy

I have the following JavaScript Regex

我有以下 JavaScript 正则表达式

As used in http://regexpal.com/

http://regexpal.com/ 中使用

\[.*(\.jpg|\.png|\.gif|\.bmp|\.jpeg).*\]

\[.*(\.jpg|\.png|\.gif|\.bmp|\.jpeg).*\]

As use in jQuery code -

在 jQuery 代码中使用 -

post.html().match(/\[.*(\.jpg|\.png|\.gif|\.bmp|\.jpeg).*\]/g);

post.html().match(/\[.*(\.jpg|\.png|\.gif|\.bmp|\.jpeg).*\]/g);

This is the sample data I am working with

这是我正在使用的示例数据

  1. [cid:[email protected]]
  2. s[cid:[email protected]]<
  3. image.jpg
  4. [cid:[email protected]]
  5. [cid:[email protected]]
  6. [cid:[email protected]]
  7. [[cid:[email protected]]
    And again
    [cid:[email protected]]]
  8. test.gif
  1. [cid:[email protected]]
  2. s[cid:[email protected]]<
  3. 图片.jpg
  4. [cid:[email protected]]
  5. [cid:[email protected]]
  6. [cid:[email protected]]
  7. [[cid:[email protected]]
    又是
    [cid:[email protected]]]
  8. 测试.gif

My issue is that on line 7, I would like the two strings enclosed in the [] to be separate, at the moment it is treating the whole line as a match,

我的问题是在第 7 行,我希望 [] 中包含的两个字符串分开,目前它将整行视为匹配,

回答by KARASZI István

You need to modify your regexp to change the greediness (note the .*?):

你需要修改你的正则表达式来改变贪婪(注意.*?):

\[.*?(\.jpg|\.png|\.gif|\.bmp|\.jpeg).*?\]