Search code examples
javascriptregex-groupregexp-replace

Accomodate multiple values using regex in Javascript


I have regex string /^(?:\[)(.*)(?:\|)(.*)(?:\|)(.*)(?:\|)(.*)(?:\|)(.*)(?:\])$/ that captures the following value [john|doe|doe@email.com|doe_avatar|manager]. I also like to capture the value with [john|doe|doe@email.com|doe_avatar] using the same regex for both. How can I do that in Javascript?


Solution

  • Yes, this is doable with a single regex, by enclosing the last segment and its accompanying pipe \| in an additional, optional, non-capturing group ((?:……)?).

    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))

    As @CertainPerformance mentions below, the results from the final capturing group will be undefined if the match isn't present