Javascript Regex在测试时返回组,但不在代码中?
我使用以下代码从一段文本中提取三个组:Javascript Regex在测试时返回组,但不在代码中?,javascript,regex,coffeescript,Javascript,Regex,Coffeescript,我使用以下代码从一段文本中提取三个组: #sample test string: 'Photo Badge <img src="https://res.cloudinary.com/surveyplanet/image/upload/v1384554966/gdm1z8joraciwjszpygg.png">' pattern = /// (.*) #Match all text before the image tag <img\
#sample test string: 'Photo Badge <img src="https://res.cloudinary.com/surveyplanet/image/upload/v1384554966/gdm1z8joraciwjszpygg.png">'
pattern = ///
(.*) #Match all text before the image tag
<img\ssrc="(.*)"> #Match the image tag and extract the image URL
(.*) #Match all text after the image tag
///g
_.map question.choices, (choice) ->
[pre, url, post] = choice.choice_text.match(pattern)[1..3]
console.log 'pre', pre
console.log 'post', post
console.log 'url', url
#示例测试字符串:“照片徽章”
模式=///
(.*)#匹配图像标记前的所有文本
#匹配图像标记并提取图像URL
(.*)#匹配图像标记后的所有文本
///g
_.地图问题.选项,(选项)->
[pre,url,post]=choice.choice\u text.match(模式)[1..3]
console.log“pre”,pre
console.log“post”,post
console.log“url”,url
出于某种原因,无论我传入什么,唯一要填充的组是
pre
。我测试了与预期相同的regex和it组。有人知道为什么会发生这种情况吗?这似乎是由于您将其分解到每一行的方式造成的
我认为在你的情况下,你实际上是在说
(.*)\n<img\ssrc="(.*)">\n(.*)
(.*)\n\n(.*)
这就解释了为什么pre匹配而其他不匹配
我不知道Java是否是这样的,但我在x++中做了类似的事情,这就是我的问题。问题是RegExp中的
g
标志。根据MDN JS文档,当出现g
标志时,会有不同的行为
因此,不是返回所有捕获组,String::match
返回在字符串中找到的所有匹配项
您的问题有两种解决方案:
- 删除
标志(无论如何,您为什么需要它?)g
- 使用
代替pattern.exec(str)
str.match(pattern)