Regex - dynamically creating pattern issue

D

Deanna

I'm trying to use Regex.Replace to replace a single word in a string,
but I have to pass in the string. It won't ever match, but if I hard-
code the word it works fine. Please help!!

string stringToAlter = "ab cd ef gh";

// --- Pattern entered as string works fine
string pat1 = @"\bcd\b";
string newStg1 = Regex.Replace(stringToAlter, @pat1, "xxx");
WriteLine("first try = " + newStg1);

// --- But passing in the word and concatenating doesn't!
string pat2 = @"\b" + "cd" + "\b";
newStg1 = Regex.Replace(stringToAlter, @pat2, "xxx");
WriteLine("second try = " + newStg1);

results:
first try = ab xxx ef gh
second try = ab cd ef gh
 
Y

Yota

I'm trying to use Regex.Replace to replace a single word in a string,
but I have to pass in the string. It won't ever match, but if I hard-
code the word it works fine. Please help!!

string stringToAlter = "ab cd ef gh";

// --- Pattern entered as string works fine
string pat1 = @"\bcd\b";
string newStg1 = Regex.Replace(stringToAlter, @pat1, "xxx");
WriteLine("first try = " + newStg1);

// --- But passing in the word and concatenating doesn't!
string pat2 = @"\b" + "cd" + "\b";
newStg1 = Regex.Replace(stringToAlter, @pat2, "xxx");
WriteLine("second try = " + newStg1);

results:
first try = ab xxx ef gh
second try = ab cd ef gh

You neglected to add the '@' to the second "\b" in your pattern. It
should be...
string pat2 = @"\b" + "cd" + @"\b";

Also, I could be wrong, but isn't the '@' unnecessary when accessing
the variable?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Deanna said:
I'm trying to use Regex.Replace to replace a single word in a string,
but I have to pass in the string. It won't ever match, but if I hard-
code the word it works fine. Please help!!

string stringToAlter = "ab cd ef gh";

// --- Pattern entered as string works fine
string pat1 = @"\bcd\b";
string newStg1 = Regex.Replace(stringToAlter, @pat1, "xxx");
WriteLine("first try = " + newStg1);

// --- But passing in the word and concatenating doesn't!
string pat2 = @"\b" + "cd" + "\b";

Change "\b" to @"\b".
newStg1 = Regex.Replace(stringToAlter, @pat2, "xxx");
WriteLine("second try = " + newStg1);

results:
first try = ab xxx ef gh
second try = ab cd ef gh

If the string might contain characters that have any special meaning in
a regular expression, use the Regex.Escape method on when creating the
pattern.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Yota said:
Also, I could be wrong, but isn't the '@' unnecessary when accessing
the variable?

Correct. It can be used if you need to use a keyword as variable name,
like @class, but I have yet to see any situation where this really would
be needed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top