niklr
niklr

Reputation: 1701

Find and replace a specific number with regex

I have the following string

string absoluteUri = "http://localhost/asdf1234?$asdf=1234&$skip=1234&skip=4321&$orderby=asdf"

In this string I would like to replace '$skip=1234' with '$skip=1244'

I have tried the following regular expression:

Regex.Replace(absoluteUri, @"$skip=\d+", "$skip=1244");

Unfortunately this is not working. What am I doing wrong?

The output should be:

"http://localhost/asdf1234?$asdf=1234&$skip=1244&skip=4321&$orderby=asdf"

Upvotes: 1

Views: 90

Answers (2)

Dmitresky
Dmitresky

Reputation: 576

I can't add comment. Just little fix. Need to do:

absoluteUri = Regex.Replace(absoluteUri, @"\$skip=\d+", "$skip=1244");

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120644

$ is a special character in regular expressions (it's an anchor). You need to escape it in both the expression and in the replacement string, but they are escaped differently.

In the regular expression, you escape it with a \ but in the substitution you escape it by adding another $:

Regex.Replace(absoluteUri, @"\$skip=\d+", "$$skip=1244");

Upvotes: 4

Related Questions