2

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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)))

2 Comments

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. Thanks
@dsrekab I've added another solution that should work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.