Regular expressions: Replacing whole words without replacing non word chararcters

L

leeonions

Hi there,
i am trying to use regular expressions to search through a text string
and replace a given whole word.

take the string = "The matsat on the mat!" (bad example i know)

i want to replace the whole word 'mat' with the word 'cat' to give
"The matsat on the cat!"

(matsat was not replaced as only whole word match, cat on the other
hand is replace because non-word characters i.e. !, are allowed)

Given below is the closest i've got using RegExp.replace, with the
following expression
Dim exp As String = "(^|\W+)(mat)($|\W+)"

This correctly identifies whole words (with surrounding non word
charaters) but also replaces the non word characters in the string,
which i wish to preserve.

Can anyone suggest a viable work around or a regular expression that
will match against part of a string without replace the entire of it.
Thanks in advance....
Cheers,
Lee
 
D

Dragon

Hi Lee,

If I understand you correctly, then this should help you:

~
exp = "\bmat\b"
~

Roman
 
S

steve

\bmat\b

try also looking at:

http://aspnet.4guysfromrolla.com/articles/022603-1.aspx

paying attention to lookahead and lookbehind...if your example is a
simplification of something much more complex than "the matsat on the cat!".

hth,

me


| Hi there,
| i am trying to use regular expressions to search through a text string
| and replace a given whole word.
|
| take the string = "The matsat on the mat!" (bad example i know)
|
| i want to replace the whole word 'mat' with the word 'cat' to give
| "The matsat on the cat!"
|
| (matsat was not replaced as only whole word match, cat on the other
| hand is replace because non-word characters i.e. !, are allowed)
|
| Given below is the closest i've got using RegExp.replace, with the
| following expression
| Dim exp As String = "(^|\W+)(mat)($|\W+)"
|
| This correctly identifies whole words (with surrounding non word
| charaters) but also replaces the non word characters in the string,
| which i wish to preserve.
|
| Can anyone suggest a viable work around or a regular expression that
| will match against part of a string without replace the entire of it.
| Thanks in advance....
| Cheers,
| Lee
|
 

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

Top