简体   繁体   English

正则表达式替换

[英]Regex for replacement

If I have an string like this: 如果我有这样的string

MyObject[0]

I want to use a RegEx to insert a () before the `[ 我想使用RegEx在`[之前插入()

So I would end up with: 所以我最终会得到:

MyObject()[0]

I used String.Replace but that could end up causing problems if there's already a () . 我使用String.Replace但是如果已经有() ,最终可能会导致问题。

.Replace("[", "()[")

Example: 例:

MyObject()[0].Items[0]

Would end up 最终会

MyObject()()[0].Items()[0]

Wanting to use a regex to do this to avoid duplication. 想要使用正则表达式来避免重复。

Regex.Replace(s, @"[A-Za-z]\[", "()[");

The problem here is it replaces the preceding character: 这里的问题是它替换了前面的字符:

MyObjec()[0]

Suggestions? 建议?

use a grouping around the AZ block in your replace to bring back your t : 在替换中的AZ块周围使用分组以恢复t

Regex.Replace(s, @"([A-Za-z])\[", "$1()[");

Test from LinqPad: 从LinqPad进行测试:

Regex.Replace("MyObject[0]", @"([A-Za-z])\[", "$1()[")

Output: 输出:

MyObject()[0]

Just look for word characters followed by [ and only replace in that case (vs. if the word characters are followed by (. 只需查找单词字符后跟[,然后仅替换这种情况(与单词字符后跟(。

For example: 例如:

 Regex.Replace(
  input, 
  //find expression
  @"(\w+)(\[)", 
  //replacement expression
  @"$1()$2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM