简体   繁体   中英

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

In simple words replace comma ',' with 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:

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"

pattern: \\"{3}.*\\"{3}
foreach regex matching this pattern 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 , "(?<=\\"\\"\\".+),(?=.+\\"\\"\\")", ";");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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