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

Accomodate multiple values using regex in Javascript

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

如果您希望每个部分都在一个单独的组中,则在 JS 中的正则表达式模式的单次迭代中是不可能的(尽管在 .NET 和其他可以提取重复组匹配的风格中是可能的)。最好的办法是匹配 [,最后匹配 ],然后再拆分 |s:

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

是的,这可以通过单个正则表达式来实现,方法是将最后一段及其随附的管道 \| 包含在一个附加的、可选的 non-capturing 组 ((?:……)?) 中。

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

const rows = [
    '[john|doe|doe@email.com|doe_avatar|manager]',
    '[jane|doe|jane@email.com|jane_avatar]',
]

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

console.log(rows.map(parse))

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