开发者

Regex : replace a string

开发者 https://www.devze.com 2023-03-14 04:01 出处:网络
I\'m currently facing a (little) blocking issue. I\'d like to replace a substring by one another using regula开发者_运维问答r expression. But here is the trick : I suck at regex.

I'm currently facing a (little) blocking issue. I'd like to replace a substring by one another using regula开发者_运维问答r 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!


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


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#


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号