正向预测捕获过多 JS

问题描述

我正在努力在字符串中“notes:”之后出现的任何日期之前插入换行符。
我的正则表达式似乎在 "notes:"
之后的第一个日期之前捕获所有文本 非常感谢您对 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> $&'));

参见regex demo

正则表达式匹配

  • (?<=notes:.*?) - 字符串中紧跟在 notes: 前面的位置,以及尽可能少的除换行符以外的零个或多个字符
  • \b - 单词边界(如果要匹配粘在字母、数字或下划线上的日期,请省略)
  • \d{1,2} - 一位或两位数字
  • ([-\/]) - 第 1 组:-/
  • \d{1,2} - 一位或两位数字
  • \1 - 与第 1 组相同的值,-/
  • \d{4} - 四位数字
  • \b - 单词边界(如果要匹配粘在字母、数字或下划线上的日期,请省略)

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