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.
CodePudding user response:
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])
}
CodePudding user response:
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);