javascript - 积极的前瞻捕获过多的 JS
问题描述
我正在努力在字符串中“注释:”之后出现的任何日期之前插入换行符。
我的正则表达式似乎在“注释:”之后的第一个日期之前捕获所有文本:
非常感谢 JavaScript 的任何帮助。
const mystring = 'wed and thurs and notes: are just so interesting 02-03-2019 on a new line please 04-05-2020 on another line please'
mystring.replaceAll(/(?<=notes:).*?(\d{1,2}-\d{1,2}-\d{4})/g, function(capture){
return '<br>' + capture;
}
);
我想要的输出:
wed and thrus and notes: are just so interesting <br> 02-03-2019 on a new line please <br> 04-05-2020 on another line please
解决方案
您可以使用
const mystring = 'wed and thurs and notes: are just so interesting 02-03-2019 on a new line please 04-05-2020 on another line please wed and thurs and notes: are just so interesting 02/03/2019 on a new line please 04/05/2020 on another line please';
console.log(mystring.replace(/(?<=notes:.*?)\b\d{1,2}([-\/])\d{1,2}\1\d{4}\b/g, '<br> $&'));
请参阅正则表达式演示。
正则表达式匹配
(?<=notes:.*?)
- 字符串中紧接在前面的位置notes:
以及除换行符之外的任何零个或多个字符尽可能少\b
- 一个单词边界(如果你想匹配粘在字母、数字或下划线上的日期,请省略)\d{1,2}
- 一位或两位数([-\/])
- 第 1 组:-
或/
\d{1,2}
- 一位或两位数\1
- 与第 1 组中的值相同,-
或/
\d{4}
- 四位数\b
- 一个单词边界(如果你想匹配粘在字母、数字或下划线上的日期,请省略)
替换模式中的$&
构造是对整个匹配的反向引用。
推荐阅读
- android - RecyclerView 适配器在设备旋转后不更新视图
- mysql - 我应该为任何异步操作调用单独的 goroutine 吗?
- java - 通过API获取所有corda账号
- makefile - Makefile 模式将所有源文件编译为可执行文件
- sql - 未定义类型的案例语句?或为什么约会?
- php - 接受协议中的任何数字类似
- c++ - C++;如何在函数中写入opencv的Vect3b指针
- php - 无法从表名中的大写字母替换为小写字母的 mySQL 表中读取数据 (PHP) (Wo_Langs -> wo_langs)
- c - 如何获取 *chars 并返回非整数?
- javascript - 有一种方法可以解决“警告:列表中的每个孩子都应该有一个唯一的“键”?