Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Regex Match whole words

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.

like image 667
tvr Avatar asked Apr 17 '11 06:04

tvr


People also ask

What is C in simple words?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Is C or C++ same?

The main difference between C and C++ is that C is a procedural programming language that does not support classes and objects. On the other hand, C++ is an extension of C programming with object-oriented programming (OOP) support.


3 Answers

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_]

like image 102
Ed Chapel Avatar answered Nov 16 '22 00:11

Ed Chapel


Keep it simple: why not just try \w*TEST\w* as the match pattern.

like image 39
mousio Avatar answered Nov 15 '22 23:11

mousio


I get the results you are expecting with the following:

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

var m = Regex.Matches(s, @"(\w*TEST\w*)", RegexOptions.IgnoreCase);
like image 2
arcain Avatar answered Nov 15 '22 23:11

arcain