在以下情况下,我需要一个能吸引作者的正则表达式
this.yourService.obtenerPrestamos().subscribe((data) => {
console.log(data)
})
Letter from author to recipient regarding topic 11-10-2018
我尝试遵循suggestions found here,这就是我所拥有的:
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)
返回'null'。
我在Chrome上使用了此功能,因为并非所有浏览器都支持向后看。有什么建议吗?
答案 0 :(得分:3)
不需要“自动”组合它们,只需在最后一部分使用or运算符即可。
(?<=from )(.+?)(?=,| to)
https://regex101.com/r/xzlptd/2/
要使其在所有浏览器中都能正常工作,请摆脱后顾之忧
from (.+?)(?:,| to)
并从比赛中选择第一组:.match(...)[1]
答案 1 :(得分: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));