如何通过正则表达式匹配或捕获给定字符串中的特定子字符串模式?

How to match or capture a specific substring-pattern from a given string via regex?

如何通过正则表达式从消息中删除密码? 以及我如何在函数中使用它,因为代码重复不是一个好主意? 现在我通过这样的切片来做:

  message.html.body.slice(14,24));

消息输出:

  html: MessageContent {
    links: [],
    images: [ [Image] ],
    body: 'Your password 5gIlrjtxDy<img src="some link />'
  },

我正在尝试这样做:

const [_, retailerPassword] = retailerMessage.html.body.trim().match(/Your\s+password\s+(\w+)/);
  console.log(retailerPassword);

const [_, recipentPassword] = recipentMessage.html.body.trim().match(/Your\s+password\s+(\w+)/);
  console.log(recipentPassword);

但之后我在重新声明块作用域变量“_”时遇到了问题。 我试着在功能上做到这一点:

const extractPassword(text:string):string => {
const [_, password] = `


Your password QfzW4zbHg4

`.trim().match(/Your\s+password\s+(\w+)/);
return password
}

您可以为此使用字符串替换方法。

此外,块范围变量重新声明问题可能是因为您正在更改消息对象;如果是这样,复制字符串应该可以解决问题。

像这样:

const retailerStr = retailerMessage.html.body;
const pass = retailerStr.replace(/Your\s+password\s+(\w+)(.*)/,'');
// pass === "5gIlrjtxDy"

OP 的主要问题来自以下组合...

  • 通过 const 两次使用相同的解构赋值模式,因此与第二个 _ 赋值冲突。

  • 使用_是因为使用了密码捕获组,它是match方法结果数组的第2个条目;因此被迫以某种方式包含第一个条目,这是正则表达式匹配,通过将它分配给永远不会被使用的 _-variable.

完全不使用解构赋值就可以很容易地解决这个问题。一个简单地写...

const retailerPassword = retailerMessage
  .html.body.trim().match(/Your\s+password\s+(\w+)/)[1];

const recipentPassword = recipentMessage
  .html.body.trim().match(/Your\s+password\s+(\w+)/)[1];

备注

一种更通用的 and/or 与语言无关的方法,例如... /(?<=\s)\w+(?=<img)/ or even simpler /\S+(?=<img)/ ... 可以尝试 ...

  • 匹配任何非空格的内容(对于不允许空格的密码)
  • 直到下一个匹配将是字符序列 '<img' ...

const retailerMessage = {
  html: {
    links: [],
    images: [ [Image] ],
    body: 'Your password 5gIlrjtxDy<img src="some link />',
  }
};

const retailerPassword = retailerMessage
  // // [https://regex101.com/r/jwAf0r/2]
  // .html.body.trim().match(/(?<=\s)\w+(?=<img)/);
  // [https://regex101.com/r/jwAf0r/1]
  .html.body.trim().match(/\S+(?=<img)/)[0];

console.log({ retailerPassword });
.as-console-wrapper { min-height: 100%!important; top: 0; }

编辑

...因为 OP 确实要求...

function getPasswordFromMessage(message) {

  // // [https://regex101.com/r/jwAf0r/2]
  // .html.body.trim().match(/(?<=\s)\w+(?=<img)/);

  // [https://regex101.com/r/jwAf0r/1]
  return message?.html?.body?.trim()?.match(/\S+(?=<img)/)?.[0] ?? null;
}

const retailerMessage = {
  html: {
    links: [],
    images: [],
    body: 'Your password 5gIlrjtxDy<img src="some link />',
  }
};
const recipientMessage = {
  html: {
    links: [],
    images: [],
    body: 'Your password FooBarBIZ<img src="some link />',
  }
};

const retailerPassword = getPasswordFromMessage(retailerMessage);
const recipientPassword = getPasswordFromMessage(recipientMessage);
const failedGetPassword = getPasswordFromMessage({});

console.log({
  retailerPassword,
  recipientPassword,
  failedGetPassword,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }