javascript - 如何通过正则表达式匹配或捕获给定字符串中的特定子字符串模式?
问题描述
如何通过正则表达式从消息中删除密码?以及如何在功能中使用它,因为代码重复不是一个好主意?现在我通过这样的切片来做:
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
}
解决方案
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; }
推荐阅读
- r - 用于读取多个 csv (tsv) 文件的 R 进度条
- r - R:修改一个以来自多个先前行的数据为条件的变量
- rest - VSTS 使用 API 在排队时设置构建参数
- android - Android Webview SwipeRefreshLayout 不允许向下滚动
- qt5 - Gumstix Overo SSD1306 OLED
- mysql - 仅检索单个记录的 Node.js MySQL 代码有什么问题
- elasticsearch - Elasticsearch hits.total 与 OR 不同
- r - 在 ggduo 散点图矩阵中显示相关指数
- angular - nouislider angular 2 格式工具提示
- android - 无法停止从后台服务启动的蓝牙适配器