简体   繁体   English

c#中的正则表达式字符串替换

[英]Regex string replace in c#

I have one string like 我有一个字符串

var input =  "data1, data2, 1233456,  \"\"\" test, data, here \"\"\", 08976, test data"

I want to replace \\"\\"\\" test, data, here \\"\\"\\" part of this string with test; data; here 我想用\\"\\"\\" test, data, here \\"\\"\\"替换\\"\\"\\" test, data, here \\"\\"\\"这个字符串的一部分test; data; here test; data; here

In simple words replace comma ',' with semincolon ';' 简单来说','用semincolon ';'替换逗号',' ';' any string inside \\"\\"\\" block only. \\"\\"\\"块内的任何字符串。

I am trying to do this with a Regular expression. 我试图用正则表达式来做这件事。

I am trying to use following regex - \\[\\\\\\\\\\"](.+)[\\\\\\\\\\"] 我正在尝试使用以下正则表达式 - \\[\\\\\\\\\\"](.+)[\\\\\\\\\\"]

Just for reference, if you want a non-regex solution to compare, you can do this with LINQ as well: 仅供参考,如果您想要比较非正则表达式解决方案,您也可以使用LINQ执行此操作:

input= string.Join("\"\"\"", 
         input.Split(new []{"\"\"\""}, StringSplitOptions.None)
         .Select( (s,i) => i % 2 == 1 ? s.Replace (',', ';') : s)
       );

Thanks guy for help, 谢谢你的帮助,

Your answers were useful. 你的答案很有用。

Finally managed to do this with following code with help of this link 最后,在此链接的帮助下,通过以下代码设法完成此操作

//My input string
var input  = Regex.Replace(input  , "[\\\"](.+)[\\\"]", ReplaceMethod);


//Method used to replace 
public static string ReplaceMethod(Match m)
    {
        string newValue = m.Value;
        return newValue.Replace("\"", "").Replace(",", ";");
    }

I don't think it is possible to do this with regex for this string: 我不认为用这个字符串的正则表达式可以做到这一点:
data1, 1233456, """ test, data, here """, 08976, test, """ second, data """, aso

It is possible for: 有可能:
data1, 1233456, < test, data, here >, 08976, test, < second, data >, aso

but not "xxx" 但不是“xxx”

pattern: \\"{3}.*\\"{3} pattern: \\"{3}.*\\"{3}
foreach regex matching this pattern string.replace(',', ';') foreach正则表达式匹配此模式string.replace(',',';')

but i'm trying to make regex... 但我正在尝试制作正则表达式......
and I give up :/ 我放弃了:/

The following code is might satisfy the requirement... 以下代码可能满足要求......

var output = Regex.Replace(input , "(?<=\\"\\"\\".+),(?=.+\\"\\"\\")", ";"); var output = Regex.Replace(input,“(?<= \\”\\“\\”。+),(?=。+ \\“\\”\\“)”,“;”);

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

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