积极的前瞻捕获了太多的 JS
Positive lookahead capturing too much 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}\d{4}\b/g, '<br> $&'));
参见regex demo。
正则表达式匹配
(?<=notes:.*?)
- 字符串中紧接 notes:
和除换行符以外的零个或多个字符尽可能少的位置
\b
- 单词边界(如果要匹配粘贴到字母、数字或下划线的日期,请省略)
\d{1,2}
- 一位或两位数
([-\/])
- 第 1 组:-
或 /
\d{1,2}
- 一位或两位数
</code> - 与组 1 中的值相同,<code>-
或 /
\d{4}
- 四位数
\b
- 单词边界(如果要匹配粘贴到字母、数字或下划线的日期,请省略)
替换模式中的 $&
构造是对整个匹配的反向引用。
我正在努力在字符串中“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}\d{4}\b/g, '<br> $&'));
参见regex demo。
正则表达式匹配
(?<=notes:.*?)
- 字符串中紧接notes:
和除换行符以外的零个或多个字符尽可能少的位置\b
- 单词边界(如果要匹配粘贴到字母、数字或下划线的日期,请省略)\d{1,2}
- 一位或两位数([-\/])
- 第 1 组:-
或/
\d{1,2}
- 一位或两位数</code> - 与组 1 中的值相同,<code>-
或/
\d{4}
- 四位数\b
- 单词边界(如果要匹配粘贴到字母、数字或下划线的日期,请省略)
替换模式中的 $&
构造是对整个匹配的反向引用。