1

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"

2 Answers 2

4

$ 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");
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thank you! The escaping with \ did the trick. I'm not sure why but it works with and without escaping the replacement string.
Probably because $s is not a valid replacement string and it ignores it. I'd recommend using $$ in the replacement even if it is not strictly necessary in this case.
0

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

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

Comments

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.