John Smith
John Smith

Reputation: 4516

how do I write a regular expression that does the following?

assuming that the word "ABC" is a keyword,

and that the regex pattern is

[^a-z^A-Z]ABC[^a-z^A-Z]

I want the following input to return true:

 hello how are you ABC hello how are you
 hello how are you.ABC0hello how are you

And the following input to return false:

"hello how are youABChello how are you"

The problem is that if "ABC" occurs at the beginning or the end of string, the regex doesn't pick it up. And if I instead of writing [^a-z^A-Z] I write [^a-z^A-Z]* then the kind of strings that I don't want will be picked up as well.

What's the proper way to write this regular expression?

Upvotes: 0

Views: 60

Answers (1)

Matt Varblow
Matt Varblow

Reputation: 7881

Use negative lookbehind and lookahead assertions:

var pattern = new Regex("(?<![a-zA-z])ABC(?![a-zA-z])");

See: http://msdn.microsoft.com/en-us/library/az24scfc.aspx#grouping_constructs

Upvotes: 2

Related Questions