2

According to this link Search for “whole word match” with SQL Server LIKE pattern

I want to follow the same query string but in a datatable I've written the following statement

Assume datatable contains the following records

datatable[0]["src"]="tst";
datatable[1]["src"]="tst,";
datatable[2]["src"]="tst:";
datatable[3]["src"]="disney";

int p=datatable.AsEnumerable().Select(a => Regex.IsMatch(a["src"].ToString(), "[^a-z]windows[^a-z]")).Count();

but the result was p = 4 while this word 'windows' exists only 3 times

And in case of using 'where' instead of 'select' as following

int p=datatable.AsEnumerable().Where(a => Regex.IsMatch(a["src"].ToString(), "[^a-z]windows[^a-z]")).Count();

p is always 0

What's wrong in my statement ..Any advice?!

Community
  • 1
  • 1
user690069
  • 330
  • 4
  • 13
  • 1
    I don't understand what you mean by *"the result was p = datatable rows count while this word 'windows' doesn't exist in all rows"* Are you saying that it's returning a count of all rows, and not a count of only the rows containing the word "windows"? – Robert Harvey Feb 14 '13 at 19:17
  • this statement returns all datatable rows count while the key word 'windows' exist in some of these rows not all of them – user690069 Feb 14 '13 at 19:18
  • Sorry, but I'm still not clear what you mean. Tell us what you expect p to contain, and what it actually contains. – Robert Harvey Feb 14 '13 at 19:19
  • 2
    Your second example will work, if you can fix your regex so that you get matches. Check your regex here: http://regexpal.com/. See also [How to match whole words with a regular expression](http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/). – Robert Harvey Feb 14 '13 at 19:33

2 Answers2

2

Your first example (Select) runs the operation on all rows in the data table. The result would be a list of Boolean values indicating whether the row value matched the expression.

In both cases, your pattern is requiring a non-alpha in front of and after the word "windows", which results in it not matching. In the first case, you would get a list containing 4 "false" values, and in the second you get nothing.

I believe the simplest regex to get what you want is probably something like:

"\bwindows\b"

(Using Robert Harvey's suggested regex. This pattern asserts that there is a "word break" - including nothing - before and after the word.)

GalacticCowboy
  • 11,663
  • 2
  • 41
  • 66
0

Select and Where aren't interchangeable - your select will return a true or false value for each record, which is why your count is 4 (because you have 4 records and thus 4 return values.

Your where clause returning 0 tells me your RegEx is not matching values 0-2. I would verify that the RegEx works as expected.

D Stanley
  • 149,601
  • 11
  • 178
  • 240