Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very simple regex not working

I have read that to match a word inside of a string using Regular expressions (in .NET), I can use the word boundary specifier (\b) within the regex. However, none of these calls result in any matches

Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", @"\b@p1\b");

Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", @"\bINSERT\b");

Is there anything I am doing wrong ?

EDIT: The second one is already working ;)

like image 469
Tomas Vana Avatar asked Mar 30 '10 11:03

Tomas Vana


1 Answers

Update: As another answer pointed out, @ is not a word character so there is no word boundary between @ and space. As a workaround, you could instead use a negative lookbehind:

@"(?<!\w)@p1\b"

Original answer: You need a @ in front of your regular expressions:

@"\b@p1\b"

Without this, the string "\b" is interpreted as a backspace (character 8), not a regular expression word boundary. There is more information about @-quoted string literals on MSDN.

An alternative way without using @-quoted string literals is to escape your backslashes:

"\\b@p1\\b"
like image 185
Mark Byers Avatar answered Oct 02 '22 15:10

Mark Byers