RegEx Replacement patterns

C

CodeSponge

Hey guys,

I'm working with a regular expression to replace patterns in a given
string. however I want to replace the patterns with another pattern
using submatch references.

ie:
if my search pattern was
"(\s)ks ?#?(\d*)(\s)"

and my replacement pattern was
"\1KS \2\3"

I would expect " ks#12 " or " kS12 " to convert to " KS 12 "

The regEx object has a replace method but it does the replacement as a
literal string copy of the replacement pattern instead of using the
submatches.
This is easy to do with most other regEx implimentations I can think
of.
any Ideas?

thanks in advance
Shaun
 
C

CodeSponge

I wanted to make sure I wasn't blowing smoke so I went and checked up
on some implementations to make sure its not just a linux thing and
there are alot of windows apps (like TextPad which uses a search
window) that accepts both a search pattern and a replacment PATTERN
(not just a string). I looked more into the regex object and it has
submatches but it looks like the only way to access them is
programaticly and not using an expression. I don't know, regex's are
such a powerful tool that u would think it would have a more complete
and integrated implementation in VB. does anyone know of a way short of
reinventing the wheel to acomplish this??
 
C

CodeSponge

hehe I kinda feel like I'm talking to myself.
My reath must stink :-o
Anyway, for those of you who are interested I found the answer.
For some reason when you are referring to a submatch in the replacment
pattern for a VB regular expression instead of using the \1 format you
have to use the $1 format.
personaly I think this is dumb but who am I to judge ;)

so if my search pattern is:
"(\s)ks ?#?(\d*)(\s)"

then my replacement pattern should be:
"$1KS $2$3"
 
H

Harlan Grove

CodeSponge said:
For some reason when you are referring to a submatch in the replacment
pattern for a VB regular expression instead of using the \1 format you
have to use the $1 format.
personaly I think this is dumb but who am I to judge ;)

so if my search pattern is:
"(\s)ks ?#?(\d*)(\s)"

then my replacement pattern should be:
"$1KS $2$3"

You're suffering from sed-think. While perl supports \<digit> backreferences
in the RHS of s///, man perlre(1) is clear that $<number> is preferred. MSFT
seems to have decided to implement only the preferred perl syntax.
 

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