2

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?

1 Answer 1

2

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

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

RegEx Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Anubhav..it worked. but could you please tell me what does (?<![)(?: and (?!]) do.I din't get how it works.
You're welcome. Link I provided has explanation of this regex on RHS. Also look at this very helpful article on lookarounds in regex: regular-expressions.info/lookaround.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.