javascript - 正则表达式搜索因特殊字符而失败
问题描述
我正在尝试在 JavaScript 中进行正则表达式搜索,但它不适用于特殊字符,例如$
and +
。
var string = "Keto After 50 $20 CPA+FS";
string.search(/Keto After 50 $20 CPA F+S/g);
我期望匹配和结果为 0 而不是 -1。
解决方案
欢迎!
我们可能只想逃避 metachars:
(Keto After 50 \$20 CPA\+FS)
测试
const regex = /(Keto After 50 \$20 CPA\+FS)/gm;
const str = `Keto After 50 \$20 CPA+FS`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
请参阅此演示以获取更多信息。
推荐阅读
- matplotlib - 嵌入式 IPython 中的 matplotlib.plot 立即显示绘图,没有机会修改返回的轴
- matlab - Matlab范数函数向向量添加了一个额外的元素?
- sql - 如何从参考行中获取 m 条记录和 n 条记录之间的记录 - 非顺序数据
- javascript - 在 javascript 中使用带有嵌套元素的 map\reduce
- c# - c#可以通过串口发送数据但不能接收
- linux - 如何自动登录 Linux 服务器并在网站上运行 git fetch/pull?
- sql - SQLite 在一行中返回多行
- pdf - 是否有任何 pdf 工具或 git 项目可以将 pdf 免费注释转换为文本注释?
- android - 在 Android 中以编程方式打开“添加 WiFi 网络”屏幕
- python - Pandas Apply/Lambda 返回数据框而不是单行