在Javascript中使用正则表达式容纳多个值

问题描述

我有正则表达式字符串/^(?:\[)(.*)(?:\|)(.*)(?:\|)(.*)(?:\|)(.*)(?:\|)(.*)(?:\])$/,它捕获以下值[john|doe|[email protected]|doe_avatar|manager]。 我还喜欢使用[john|doe|[email protected]|doe_avatar]来为两者使用相同的正则表达式来捕获值。如何在 JavaScript 中做到这一点?

解决方法

如果您希望每个部分都位于单独的组中,则不可能在JS中的正则表达式模式的单次迭代中进行(尽管在.NET和其他可提取重复组匹配的代码中,这是可能的)。您将能够管理的最好的情况是匹配[,最后匹配],然后再按|进行拆分:

const extract = (str) => {
  const insideBrackets = str.match(/\[([^\]]+)\]/)[1];
  const sections = insideBrackets.split('|');
  console.log(sections);
};
extract('[john|doe|[email protected]|doe_avatar|manager]');
extract('[john|doe|[email protected]|doe_avatar]');

,

是的,这可以通过单个正则表达式来实现,方法是将最后一个段及其随附的管道\|封闭在另一个可选的非捕获组((?:……)?)中。

const regex =
    /^(?:\[)(.*?)(?:\|)(.*?)(?:\|)(.*?)(?:\|)(.*?)(?:(?:\|)(.*?))?(?:\])$/

const rows = [
    '[john|doe|[email protected]|doe_avatar|manager]','[jane|doe|[email protected]|jane_avatar]',]

const parse = str => {
    const m = str.match(regex)
    
    if (!m) return null
    
    const [fullMatch,forename,surname,email,avatar,role] = m
    
    return { fullMatch,role }
}

console.log(rows.map(parse))

正如@CertainPerformance在下面提到的,如果不存在匹配项,则最终捕获组的结果将为undefined