首页 > 解决方案 > 积极的前瞻捕获过多的 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

标签: javascriptregexreplacereplaceall

解决方案


您可以使用

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- 一个单词边界(如果你想匹配粘在字母、数字或下划线上的日期,请省略)

替换模式中的$&构造是对整个匹配的反向引用。


推荐阅读