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.
>Solution :
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])
}