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: match everything but a given string and do not match single characters from that string

Let’s start with the following input.

Input = 'blue, blueblue, b l u e'

I want to match everything that is not the string ‘blue’. Note that blueblue should not match but single characters should (even if present in match string).
From this If I replace the matches with an empty string it should return:

Result = 'blueblueblue'

I have tried with [^\bblue\b]+
but this matches the last four single characters ‘b’, ‘l’,’u’,’e’

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

>Solution :

If you regex engine support the \K flag, then we can try:

/blue\K|.*?(?=blue|$)/gm

Demo

This pattern says to match:

  • blue match "blue"
  • \K but then forget that match
  • | OR
  • .*? match anything else until reaching
  • (?=blue|$) the next "blue" or the end of the string

Edit:

On JavaScript, we can try the following replacement:

var input = "blue, blueblue, b l u e";
var output = input.replace(/blue|.*?(?=blue|$)/g, (x) => x != "blue" ? "" : "blue");
console.log(output);
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