Concatenating a variable with a regex group match in regex.replace

Go To StackoverFlow.com

1

I am having an issue where I am using regex.Replace to replace part of a string. The basic idea is that I want to capture the beginning of the string then replace the end of the string with a value from code. For an example pretend I have a string that says "Test Number " followed by number and I want to increment that number. I capture the "Test Number " but when I try to concatenate that capture with the new number it treats the capture ($1) as a literal and replaces the entire string with $1[new number].

Dim s as String = "We are on Test Number 1"
Dim newNumber as Integer = 2

s=Regex.Replace(s,"(Test Number )(\d)","$1" & newNumber)

This will output "We are on $12". However, if I use a literal in the replace, the issue doesn't happen.

Dim s as String = "We are on Test Number 1"

s=Regex.Replace(s,"(Test Number )(\d)","$1" & "2")

This will output "We are on Test Number 2", as expected.

Does anyone have any thoughts on how I can use a variable in the replacement string portion of the Regex.Replace when including a captured group?

Thanks in advance.

2012-04-05 16:44
by dsrekab


1

Dim s as String = "We are on Test Number 1"
Dim newNumber as Integer = 2

s=Regex.Replace(s,"(Test Number) (\d)","$1 " & newNumber)

The problem is that when you concatenate, you end up specifying "$12" and of course there is no capture 12. In this case, we can take out the trailing space from "Test Number" and add it in the replacement, so our replacement string is "$1 2" and the capture replacement works as desired.

A better, more generic solution, which can also be used when no space is present, is to use the Regex.Replace overload that accepts a MatchEvaluator:

s = Regex.Replace(s, "(Test Number )(\d)",
   New MatchEvaluator(Function(m as Match)(m.Groups(1).Value & newNumber)))
2012-04-05 16:53
by Jay
Unfortunately, my actual code doesn't have a space, but I see what you did. I guess the concatenation happes first then the regex evaluation.

Thank - dsrekab 2012-04-05 17:05

@dsrekab I've added another solution that should work for you - Jay 2012-04-05 18:42


2

I just had this same issue. To fix it, escape the group number in curly braces.

s=Regex.Replace(s,"(Test Number )(\d)","${1}" & newNumber)

Here's a working dotnetfiddle sample: https://dotnetfiddle.net/1gZKNB

2015-02-27 20:04
by ps2goat
Ads