By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,239 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,239 IT Pros & Developers. It's quick & easy.

Regular expressions: Replacing whole words without replacing non word chararcters

P: n/a
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

Nov 21 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
\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
"leeonions" <le*******@yahoo.co.uk> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
| 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
|
Nov 21 '05 #2

P: n/a
Hi Lee,

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

~
exp = "\bmat\b"
~

Roman
Nov 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.