Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex select all after nth occurance of character

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading