3

VB2005: I've been looking at regex for some hours now and cant seem to get my head around the .Replace for my case. I'm looking for two fields and then I want to replace those fields with new values. So my string looks like so:

Dim myInputString as string ="RTEMP                 MIN<240  MAX<800"

My regex is

dim ptn as string = "RTEMP\s{17}MIN<(?<min>(\d|\s){1,3})\s{1,3}MAX<(?<max>(\d|\s){1,3})\s{1,12}"
Dim MyRegex As Regex = New Regex(ptn, RegexOptions.IgnoreCase)

and that works well and it captures my two fields. Now I have new values

dim newMin as integer = 300
dim newMax as integer = 999

But cant seem to figure out how to replace the two values in one swoop

Dim result As String = MyRegex.Replace(myInputString, MyRegexReplace)

What do I put in MyRegexReplace? This is a simple two value replace but Im going to have possibly more so was thinking there has got to be a way to do this but need help.

Thanks AGP

svick
  • 236,525
  • 50
  • 385
  • 514
sinDizzy
  • 1,300
  • 7
  • 28
  • 60
  • It's a bit hacky, but you could do `"(RTEMP\s{17}MIN<)(...)(\s{1,3}MAX<)(...)(\s{1,12})"` and replace with `"\1{newMin}\3{newMax}\5"`, where you've substituted newMin & newMax in. – mathematical.coffee Feb 09 '12 at 02:53
  • so this takes the first part, adds new value, middle part, adds new value, and last part? yeah i think i see how it works. but i will need to do this for 20 fields. this was just a small example. ill try it though. – sinDizzy Feb 09 '12 at 14:56

1 Answers1

0

Since you have 2 distinct values to swap into those 2 fields, wouldn't you want to use 2 separate Regex operations?

But if you want to use one Regex operation, you could use a MatchEvaluator:

Dim result As string = MyRegex.Replace(myInputString, ReplaceField)

Private Function ReplaceField(match As Match) As String
    ' Use the Index property of the Match to determine what value to use as replacement
End Function
Tom W Hall
  • 5,273
  • 4
  • 29
  • 35
  • yeah i could use two regex but this is a small example of what i have to do. in the end I am replacing 20 fields with new values. let me try this method and see how it pans out. – sinDizzy Feb 09 '12 at 14:57