alexbts
alexbts

Reputation: 15

Regex : replace a string

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!

Upvotes: 1

Views: 351

Answers (4)

DiableNoir
DiableNoir

Reputation: 644

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

Upvotes: 0

Jon
Jon

Reputation: 437326

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')");

Upvotes: 3

Xedecimal
Xedecimal

Reputation: 3223

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.

Upvotes: 0

Taryn East
Taryn East

Reputation: 27747

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#

Upvotes: 1

Related Questions