首页 > 解决方案 > 在我的 nodeJs 应用程序中使用 REGEX 时出现奇怪的问题

问题描述

我有一个文档,它是 microsoft graph db 中的一条消息,我正在尝试从正文中解析一些令牌/跟踪 nbr。所以在我的情况下,我得到信息,然后我将正文传递给我的正则表达式函数。还有我的问题,当我使用

const str =  messages.value[0].body
console.log(str)
// check if we have a tracking id in the body
const trackingId = regex.getTrackingId(str)
if(trackingId){
  console.log('We have a Tracking ID ' + trackingId)
   }

它在这里失败是我的 getTrackingId 函数

function getTrackingId(body) {

try {

    console.log(body)
 const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
 while ((m = regex.exec(body)) !== null) {
   // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
      regex.lastIndex++;
  }
  console.log(m)

if (m.length == 2) {
  return  m[1]
} else {
  return null
}
 }
} catch (error) {
console.log(error) }}

我确保文本是过去的功能,就是这样。如果我把身体变成静态的,它会起作用,所以真的不确定发生了什么?

const str = `{ contentType: 'html',
  content:
   '<html>\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\r\n<meta content="text/html; charset=us-ascii">\r\n</head>\r\n<body>\r\n<p>This is a Test Email which will be deleted</p>\r\n<img src="http://demo.example.com/campaign/xHMmLOSEpv/tracker.png">\r\n</body>\r\n</html>\r\n' }
"`;

function getTrackingId(body) {
      try {
      

     const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
     while ((m = regex.exec(body)) !== null) {
      // This is necessary to avoid infinite loops with zero-width matches
      if (m.index === regex.lastIndex) {
          regex.lastIndex++;
      }
    
    if (m.length == 2) {
      console.log('Tracking Nbr : ' + m[1])
    } else {
      console.log('No Tracking Nbr')
    }
     }
} catch (error) {
console.log(error)
}
}

getTrackingId(str)

标签: javascriptnode.jsregex

解决方案


在深入挖掘之后,我发现了这个问题。我的正则表达式代码很好。问题是,当我从 Microsoft API 获得响应并将其分配给 str 变量时,它会将其视为一个对象。由于正则表达式不喜欢这样,它永远不会匹配任何东西。

所以简单的解决方法是

const str =  JSON.stringify(messages.value[0].body)

当我尝试在 str 上做一个简单的 indexOf 并得到错误时,我得到了它。


推荐阅读