javascript - 在我的 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)
解决方案
在深入挖掘之后,我发现了这个问题。我的正则表达式代码很好。问题是,当我从 Microsoft API 获得响应并将其分配给 str 变量时,它会将其视为一个对象。由于正则表达式不喜欢这样,它永远不会匹配任何东西。
所以简单的解决方法是
const str = JSON.stringify(messages.value[0].body)
当我尝试在 str 上做一个简单的 indexOf 并得到错误时,我得到了它。
推荐阅读
- ruby-on-rails - 带有外部授权和回调的 Rails before_action
- python - 从满足条件的熊猫列中提取属性[按频率排序]
- c - 可以在一行中声明/分配一个 int* 吗?
- reactjs - NEXT JS - 如何删除查询参数
- c++ - 使用 boost::hana Y-combinator 时出现 Clang 编译器错误
- javascript - @testing-library/react (rtl) 'waitFor' 只有在没有 await 关键字的情况下才会成功
- reactjs - 在 React 中单击时更改特定按钮的文本
- android - Audio Focus 在 android 9 和 android 10 android 中不起作用?
- linux - 为什么从 666 而不是 777 中减去文件的 umask?
- r - 使用“dplyr”计算每一行数据帧的特定比率