dnclem
dnclem

Reputation: 2838

regex and string

Consider the following:

string keywords = "(load|save|close)";
Regex x = new Regex(@"\b"+keywords+"\b");

I get no matches. However, if I do this:

Regex x = new Regex(@"\b(load|save|close)\b");

I get matches. How come the former doesn't work, and how can I fix this? Basically, I want the keywords to be configurable so I placed them in a string.

Upvotes: 0

Views: 124

Answers (3)

Łukasz Wiatrak
Łukasz Wiatrak

Reputation: 2767

Regex x = new Regex(@"\b"+keywords+@"\b");

You forgot additional @ before second "\b"

Upvotes: 2

samjudson
samjudson

Reputation: 56853

The last \b in the first code snippet needs a verbatim string specifier (@) in front of it as well as it is a seperate string instance.

string keywords = "(load|save|close)"; 
Regex x = new Regex(@"\b"+keywords+@"\b");  

Upvotes: 8

Grant Thomas
Grant Thomas

Reputation: 45083

You're missing another verbatim string specifier (@ prefixed to the last \b):

Regex x = new Regex(@"\b" + keywords + @"\b");

Upvotes: 3

Related Questions