Regex在测试时返回组,但在代码中不返回

Regex returns groups when testing but not in code?

本文关键字:返回 代码 测试 Regex      更新时间:2023-09-26

我使用以下代码从一段文本中提取三组:

#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

由于某种原因,无论我传入什么,唯一填充的组都是pre。我在这里测试了相同的正则表达式,它按预期分组。有人知道为什么会这样吗?

问题是您的RegExp中的g标志。根据MDN JS文档,当g标志存在时,String::match和RegExp::exec有不同的行为。

因此,String::match不是返回所有捕获组,而是返回在字符串中找到的所有匹配。

你的问题有两个解决方案:

  • 删除g标志(为什么你需要它,无论如何?)。
  • 使用pattern.exec(str)代替str.match(pattern)

这看起来是由于你把它分解成每行的方式?

我想在你的例子中,你实际上是在说

    (.*)'n<img'ssrc="(.*)">'n(.*) 

这就解释了为什么pre是匹配的,而其他的不是。

我不知道Java是不是这样,但我在x++中做了类似的事情,这就是我的问题。