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
On Mar 23, 8:54 pm, "Deanna" <ddelapa
@gmail.com> wrote:
> 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?
> newStg1 = Regex.Replace(stringToAlter, @pat2, "xxx");
Deanna wrote:
> 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.
--
Gran Andersson
_____
http://www.guffa.com
-----------------------------------------------Reply-----------------------------------------------
Yota wrote:
> Also, I could be wrong, but isn't the '@' unnecessary when accessing
> the variable?
>> newStg1 = Regex.Replace(stringToAlter, @pat2, "xxx");
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.
--
Gran Andersson
_____
http://www.guffa.com