首页 > 解决方案 > 如何通过正则表达式匹配或捕获给定字符串中的特定子字符串模式?

问题描述

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

  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
}

标签: javascriptregexstringmatch

解决方案


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

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

  • 的使用_是由于使用了密码捕获组,它是match方法结果数组的第二个条目;因此被迫以某种方式包含第一个条目,即正则表达式匹配,通过将其分配给 never to be used _-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];

笔记

一个更通用和/或语言不可知的方法,比如....../(?<=\s)\w+(?=<img)/甚至更简单/\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; }


推荐阅读