簡體   English   中英

在Javascript中合並兩個正則表達式

[英]Combine two regular expressions in Javascript

在以下情況下,我需要一個能吸引作者的正則表達式

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

Letter from author, regarding topic 10-11-2018

我嘗試按照此處找到建議進行操作 ,這就是我所擁有的:

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上使用了此功能,因為並非所有瀏覽器都支持查找。 有什么建議么?

無需“自動”組合它們,只需在最后一部分使用or運算符即可:

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

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

要使其在所有瀏覽器中都能正常工作,請擺脫環顧四周

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

並從匹配項中選擇第一組: .match(...)[1]

除了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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM