Replace whole word with a symbol using C# Regex

So I am trying to replace a word like @theplace or @theplaces using a Regex pattern like:

String Pattern = string.Format(@"\b{0}\b", PlaceName);

But when I do the replacement, it is not finding the pattern, I am guessing it is the @ symbol that is the problem.

Can someone show me what I need to do to the Regex pattern to get it to work?

Answers


Your problem* is the \b (word boundary) before the @. There is no word boundary between a space and an @.

You could just remove it, or replace it with a non-boundary, which is a capital B.

string Pattern = string.Format(@"\B{0}\b", PlaceName);

* assuming that PlaceName begins with @.


The following code will replace any instances of @thepalace or @thepalaces with <replacement>.

var result = Regex.Replace(
    "some text with @thepalace or @thepalaces in it."
    + "\r\nHowever, @thepalacefoo and bar@thepalace won't be replaced.", // input
    @"\B@thepalaces?\b", // pattern
    "<replacement>"); // replacement text

The ? makes the preceding character, s, optional. I'm using the static Regex.Replace method. The \b matches boundaries between word and non-word characters. \B matches every boundary that \b does not. See regex boundaries.

Result

some text with <replacement> or <replacement> in it.
However, @thepalacefoo and bar@thepalace won't be replaced.

Need Your Help

Can I specify puppet's root execution directory at 'puppet apply' runtime?

amazon-web-services puppet

Suppose I'm working in AWS, and have an EBS volume attached to an instance. That volume is a copy of a root volume, insofar as it was created by snapshotting the root volume of another instance.

convert Timezone to mysql date format Y-m-d

php date timezone

I have a timezone date that have been posted to some PHP script.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.