0

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

  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – rsjaffe Apr 30 '20 at 17:00

2 Answers2

0

You can get all the separated words with the regex below:

const regex = /[^:]*\w+/g

After that you can obtain all the matches with the following:

const text = "FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234"
const matches = text.match(regex)

Finally remove the duplicates:

const uniqueArr = Array.from(new Set(matches))
console.log(uniqueArr) // ["FOO", "BAR", "123FF", "FOO", "BAR", "1234"]

Hope it helps! :)

0

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))
thibsc
  • 3,098
  • 1
  • 17
  • 29