# SQL Server query to match an exact word and replace it with another string

**URL:** <https://community.developer.atlassian.com/t/sql-server-query-to-match-an-exact-word-and-replace-it-with-another-string/20149>\
**Category:** Confluence Server\
**Tags:** confluence-server\
**Created:** [June 21, 2018, 8:28pm UTC](https://community.developer.atlassian.com/t/sql-server-query-to-match-an-exact-word-and-replace-it-with-another-string/20149 "2018-06-21T20:28:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ilakk.manoharan](https://avatars.discourse-cdn.com/v4/letter/i/977dab/32.png) [@ilakk.manoharan](https://community.developer.atlassian.com/u/ilakk.manoharan)\
**Post date:** [June 21, 2018, 8:28pm UTC](https://community.developer.atlassian.com/t/sql-server-query-to-match-an-exact-word-and-replace-it-with-another-string/20149/1 "2018-06-21T20:28:10Z")

</div>

I am using the following sql to replace all occurrences of one string with another.

Example: I want to update all occurrences of ‘test’ with ‘prod’.  
I want to avoid matching strings like ‘test123’, ‘123test’, ‘testiest’…

This is just an example. These search and replace strings are configurable.

This is the sql that I am using:  
`String sql = "UPDATE BODYCONTENT SET BODY = CAST(REPLACE(CAST(BODY as nvarchar(max)), ? , ?) as ntext) WHERE BODY like '%[^a-z0-9]' + ? + '[^a-z0-9]%' OR" + " BODY like ? + '[^a-z0-9]%' OR" + " BODY like '%[^a-z0-9]' + ? OR" + " BODY like ?";`

But here, it is matching 123test, test123, testest and updating it as 123prod, prod123 and prodprod. How can I avoid this behavior?

I am trying something similar with another database

```auto
select * from dbo.persons where LastName like '%[^a-z][^0-9]Dan[^a-z][^0-9]%' OR 
  LastName like 'Dan[^a-z][^0-9]%' OR 
  LastName like '%[^a-z][^0-9]Dan'

```

I could match all Dan and not Dan123 or 12Dan or Danville…  
Please let me know your thoughts.

---

<div class="post-metadata">

**Author:** ![Panos](https://sea1.discourse-cdn.com/atlassiandeveloper/user_avatar/community.developer.atlassian.com/panos/32/36018_2.png) [@Panos](https://community.developer.atlassian.com/u/Panos)\
**Post date:** [June 21, 2018, 9:13pm UTC](https://community.developer.atlassian.com/t/sql-server-query-to-match-an-exact-word-and-replace-it-with-another-string/20149/2 "2018-06-21T21:13:21Z")

</div>

Since you are using regex and you want to replace words consider using`\b` metacharacter:

> **[Regex Tutorial - \\b Word Boundaries](https://www.regular-expressions.info/wordboundaries.html)**
>
> In regular expressions, \\b anchors the regex at a word boundary or the position between a word and a non-word character, or vice versa.

For example `\bprod\b` pattern will match only prod, not 123prod, neither prodprod, nor prod123.  
I dont know how mysql treats though those
