【问题标题】:Positive lookahead capturing too much JS积极的前瞻捕获过多的 JS
【发布时间】:2021-03-03 12:17:03
【问题描述】:

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

【问题讨论】:

  • mystring.replace(/(?&lt;=notes:.*?)\d{1,2}-\d{1,2}-\d{4}/g, '&lt;br&gt;$&amp;')?
  • 您是否介意解释一下,我如何捕获带有“-”或“/”的日期,即 02-03-2002 或 02/03/2002

标签: javascript regex replace replaceall


【解决方案1】:

你可以使用

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

正则表达式匹配

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多