0

I have a string in the following format and I'm trying to return all the data after the 3rd occurrence of the ':' character as in the example below.

user_name_1, 10:46:36 activity_name_1 : the text to be returned

So far I have the regex \:.* that returns everything after the first occurrence, eg. :46:36 activity_name_1 : the text to be returned

If I modify it to \:{3}.* eg. to look for the 3rd instance, the regex will not return any matches. It looks like it should be a very simple query but nothing I've tried seems to work.

I've already found the following question find value after nth occurence of - using RegEx however in this case they're returning only the next 3 digits after the nth character and not the entire remaining string.

paulf
  • 65
  • 5

2 Answers2

3

I'd suggest not using regex for this. split() the string by the : character and remove the first two elements of the resulting array.

You can turn the result back in to a string if necessary by using join():

let input = 'user_name_1, 10:46:36 activity_name_1 : the text to be returned : foo : bar';

let arr = input.split(':');
arr.splice(0, 3);
console.log(arr);

let output = arr.join(':').trim();
console.log(output);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks for the reply, this is what I tried initally, however there are some scenarios where the text to be returned could also contain one or more : symbols which makes splitting and joining very messy – paulf Oct 02 '22 at 19:13
  • 1
    In that case `join()` the array back together using `:` - I edited the question to show this use case – Rory McCrossan Oct 02 '22 at 19:17
3

You can use

^(?:[^:]*:){3}\s*(\S.*)

See the regex demo. Details:

  • ^ - start of string
  • (?:[^:]*:){3} - three occurrences of any zero or more chars other than a : and then a : char
  • \s* - zero or more whitespaces
  • (\S.*) - Group 1: a non-whitespace char and then the rest of the line.

See the JavaScript demo:

const text = "user_name_1, 10:46:36 activity_name_1 : the text to be returned";
const match = text.match(/^(?:[^:]*:){3}\s*(\S.*)/)
if (match) {
  console.log(match[1])
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Just tested this and it's working perfectly for my use case, really appreciate the explanation for each selector as well! – paulf Oct 02 '22 at 19:20