ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   RegEx Replacement patterns (https://www.excelbanter.com/excel-programming/322285-regex-replacement-patterns.html)

CodeSponge[_2_]

RegEx Replacement patterns
 
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


CodeSponge[_2_]

RegEx Replacement patterns
 
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"


Harlan Grove

RegEx Replacement patterns
 
"CodeSponge" wrote...
....
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.




All times are GMT +1. The time now is 03:06 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com