【问题标题】:Combine two regular expressions in Javascript在Javascript中组合两个正则表达式
【发布时间】:2018-12-14 14:05:52
【问题描述】:

我需要一个在以下场景中选择作者的正则表达式

Letter from author to recipient regarding topic 11-10-2018

Letter from author, regarding topic 10-11-2018

我尝试关注suggestions found here,这就是我所拥有的:

let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
let combinedRegex = new RegExp(commaRegex + '|' + fromToRegex);
let author = document.getElementById('userInput').value.match(combinedRegex);
console.log(author) 

但是console.log(author) 返回“null”。

我在 Chrome 上使用它,因为并非所有浏览器都支持后视。有什么建议吗?

【问题讨论】:

  • 您是否正确阅读了这些方法?他们使用regex.source- 你也厌倦了使用它吗?
  • 你想得到哪个词?
  • @IslamElshobokshy 我正在尝试获取作者的姓名,该姓名总是会有所不同,但会在“来自”和“到”之间或在“来自”和“,”之间。跨度>

标签: javascript regex


【解决方案1】:

无需“自动”组合它们,只需在最后一部分使用 or 运算符即可:

(?<=from )(.+?)(?=,| to)

https://regex101.com/r/xzlptd/2/

要使其在所有浏览器中都能正常工作,请去掉环顾四周

from (.+?)(?:,| to)

从比赛中选出第一组:.match(...)[1]

【讨论】:

    【解决方案2】:

    除了 georg 提供的解决方案之外,以防万一您想组合其他两个不易被一个替代的解决方案:

    您必须添加源而不是整个对象:

    let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
    let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
    let combinedRegex = new RegExp(commaRegex.source + '|' + fromToRegex.source);
    
    let sampleText = 'Letter from Joseph Tribbiani to recipient regarding topic 11-10-2018';
    
    console.log(sampleText.match(combinedRegex));
    
    sampleText = 'Letter from Joseph Tribbiani, regarding topic 11-10-2018';
    
    console.log(sampleText.match(combinedRegex));

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2021-12-30
      相关资源
      最近更新 更多