Regex for replacing everything after a keyword with colon up to any other keyword with colon

Viewed 206

I have the following type of strings:

This is a test: 1, two again,three test2: what is, this
test: acid, kool-aid word: some more info
Another test: face, 3, & yes

What I'd like to do is remove test: and everything after until it hits another word that has a colon.

The result set from above would look like:

This is a test2: what is, this
word: some more info
Another

Here's what I've attempted, but this fails when there is NO word with a colon (so example 3 fails) test:.+?(?=\w+:)

3 Answers

You can use this regex for matching:

 *\btest:.*?\b(?=\w+:|$)

And replace with empty string.

RegEx Demo

RegEx Details:

  • *: Match 0 or more spaces
  • \btest: Match full word test:
  • .*?\b: Match 0 or more of any characters (lazy match) followed by a word boundary
  • (?=\w+:|$): Positive lookahead to assert that we have a word + : or end of line ahead.

You were on the right track. For the last case where there is no second word with a colon, you need to match on the end-of-line character $. So you can use:

test:.*?(?=$|\b\w+:).

Demo

With your shown samples, please try following regex. This will create 1 to 2 capturing groups, this is having 3 matches 1st from starting to just before text with colon's 1st occurrence comes, 2nd match: From text followed by colon to next occurrence of text followed by colon(no capturing group is created for this match). 3rd match: rest of the value. So in case line has only 2 matches found(nothing in value after 2nd occurrence of text colon) then it will create 1 capturing group else it will be having 2 capturing groups. Perform substitution accordingly.

^(.*?)\s*\w+:.*?(?:\w+:|$)\s*(.*)$

Online demo for above regex

Related