replace whole word

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

If i use the replace function in c#

string a = "this";
a.replace("is", "something");

my output would be like thsomething
how can i replace when only the whole word matches.

string a = "is";
a.replace("is", "something");

output: something

Thanks
Aaron
 
Use:

string a = "is";
a = Regex.Replace(a, @"\bis\b", "something");

Niki
 
what does \b mean? backspace?

what if the string is just one work "is" not " is "??
 
what is the string only has one word
a = "is";

there's no /b in that string
 
Aaron said:
what is the string only has one word
a = "is";

there's no /b in that string

Sure there is. End of string is a word boundary. Why would you think
it isn't? Remember in a regular expression, there is not necessarily a
one-to-one correlation between letter in the pattern and letters in the
matched string.
 
As explaind in the link I've sent you, "\b" is a zero-width assertion: It
doesn't match a character, it matches a position in a string where left of
the position is a word character (a-z,A-Z,0-9,_), while right of it isn't
(or vice versa). In the string "is", at position 0 there'a word character
('i') to the right, but no word character to the left, thus \b matches. Same
applies for the end of the string.

Niki
 

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

Back
Top