Search code examples
regexregex-groupcapturing-group

Regex to capture the first 5 groups and last character


I'm trying to create a regex which will extract the first 5 characters and the last character in a string no matter the size of the string. For example

For FOO:BAR:123FF:FOO:BARF:OO:BAR:1234 or FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234 it will capture six groups which is FOO BAR 123FF FOO BAR 1234


Solution

  • If your string is always formatted like this, I think it's better to use split

    let a = 'FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234'
    let res = a.split(':')
    // Remove all between the 5th and the last element
    res.splice(5, res.length - 5 - 1)
    
    console.log(res)

    But if you really want to use regex, it's also possible:

    let a = 'FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234'
    let regex = /^(\w+):(\w+):(\w+):(\w+):(\w+):.*:(\w+)$/
    
    console.log(regex.exec(a).slice(1))