C# - Regex Match whole words

tvr picture tvr · Apr 17, 2011 · Viewed 14.6k times · Source

I need to match all the whole words containing a given a string.

string s = "ABC.MYTESTING
XYZ.YOUTESTED
ANY.TESTING";

Regex r = new Regex("(?<TM>[!\..]*TEST.*)", ...);
MatchCollection mc = r.Matches(s);

I need the result to be:

MYTESTING
YOUTESTED
TESTING

But I get:

TESTING
TESTED
.TESTING

How do I achieve this with Regular expressions.

Edit: Extended sample string.

Answer

Ed Chapel picture Ed Chapel · Apr 17, 2011

If you were looking for all words including 'TEST', you should use

@"(?<TM>\w*TEST\w*)"

\w includes word characters and is short for [A-Za-z0-9_]