Jayaraman
Jayaraman

Reputation: 147

How to ignore a specific string while searching for a pattern in Regex?

I have a query where I replace all the keywords specified in the pattern with the keyword enclosed in square brackets.

if my query already has Select [key] from table1, I should ignore and avoid replacing it:

var pattern = @"(?i)Key|IN|ON|VIEW";
var subject = "Select key from table1";
var result = Regex.Replace(subject, pattern, @"[$0]");

How to achieve this?

Upvotes: 2

Views: 172

Answers (1)

anubhava
anubhava

Reputation: 786329

You can use lookaheads to ignore matching [ and ] surrounding your keywords:

var pattern = @"(?i)(?<!\[)(?:Key|IN|ON|VIEW)(?!\])";

RegEx Demo

Upvotes: 2

Related Questions