0

Possible Duplicate:
Regex to match words
Way to have String.Replace only hit “whole words”

I need do a simple regex.replace() on text with complete words.

Example: pattern to find: "kiss" word replace: "metallica"

text 1: Kiss is the rock band. Metallica is the rock band. (OK)

text 2: The boy kissed the girl. The boy metallicaed the girl. (ERROR)

I need find the exactly the same word, maybe verifying the white space before and after the word... I don't know :(

I think this is easy to do but I'm not finding the solution.

Thanks for the help.

Community
  • 1
  • 1
Leandro Brito
  • 334
  • 2
  • 13

4 Answers4

1

Use the word boundary escape \b:

@"\bkiss\b"

RegularExpressions.Info reference.

Make sure to use the ignore case option.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

for this use word boundaries \b

@"\bKiss\b"

will match only the word "Kiss" and not "kissed"

\b matches on the change from a word character to a non word character.

\w contains word characters that means all letters, digits and _

Examples:

Will match on:

Kiss, Kiss123, Kiss Kiss. Kiss@ Kiss_

Will not match on (if ignore case is used):

kissed Kisses

stema
  • 90,351
  • 20
  • 107
  • 135
  • Is it possible to replace only 1 time? On the first occurrence of word. – Leandro Brito Jan 18 '12 at 17:47
  • There exist a [very good manual](http://msdn.microsoft.com/en-us/library/6f7hht7k.aspx). You need [Regex.Replace Method (String, String, Int32, Int32)](http://msdn.microsoft.com/en-us/library/3fky5t5f.aspx), where you can specify in the 3 parameter how many replacements you want. – stema Jan 18 '12 at 21:13
0

Use this regular expression:

(?i)\bkiss\b

with word boundaries and ignore-case option.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
0

ahh i think i get what you mean. my regex is terrible but bear with me...

try (test)*

where test is the word you want to replace?

that matches testing, testy, testicles etc