1

I'm currently facing a (little) blocking issue. I'd like to replace a substring by one another using regular expression. But here is the trick : I suck at regex.

Regex.Replace(contenu, "Request.ServerVariables("*"))",
                       "ServerVariables('test')");

Basically I'd like to replace whatever is between the " by "test". I tried ".{*}" as a pattern but it doesn't work.

Could you give me some tips, I'd appreciate it!

0

4 Answers 4

3

There are several issues you need to take care of.

  1. You are using special characters in your regex (., parens, quotes) -- you need to escape these with a slash. And you need to escape the slashes with another slash as well because we 're in a C# string literal, unless you prefix the string with @ in which case the escaping rules are different.
  2. The expression to match "any number of whatever characters" is .*. In this case, you would want to match any number of non-quote characters, which is [^"]*.
  3. In contrast to (1) above, the replacement string is not a regular expression so you don't want any slashes there.
  4. You need to store the return value of the replace somewhere.

The end result is

var result = Regex.Replace(contenu,
                           @"Request\.ServerVariables\(""[^""]*""\)",
                           "Request.ServerVariables('test')");
Sign up to request clarification or add additional context in comments.

Comments

1

Based purely on my knowledge of regex (and not how they are done in C#), the pattern you want is probably:

"[^"]*"

ie - match a " then match everything that's not a " then match another "

You may need to escape the double-quotes to make your regex-parser actually match on them... that's what I don't know about C#

1 Comment

Dead right. The escaped version will look like either Regex.Replace(contenu, "Request\\.ServerVariables\\(\"[^\"]*\"\\)", "Request.ServerVariables(\"test\")"); or Regex.Replace(contenu, @"Request\.ServerVariables\(""[^""]*""\)", @"Request.ServerVariables(""test"")");
0

Try to avoid where you can the '.*' in regex, you can usually find what you want to get by avoiding other characters, for example [^"]+ not quoted, or ([^)]+) not in parenthesis. So you may just want "([^"]+)" which should give you the whole thing in [0], then in [1] you'll find 'test'.

You could also just replace '"' with '' I think.

Comments

0

Taryn Easts regex includes the *. You should remove it, if it is just a placeholder for any value:

"[^"]"

BTW: You can test this regex with this cool editor: http://rubular.com/r/1MMtJNF3kM

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.