Nikhil Chavan
Nikhil Chavan

Reputation: 1715

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

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 - \[\\\\\"](.+)[\\\\\"]

Upvotes: 1

Views: 162

Answers (4)

gpmurthy
gpmurthy

Reputation: 2427

The following code is might satisfy the requirement...

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

Upvotes: 0

Nikhil Chavan
Nikhil Chavan

Reputation: 1715

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(",", ";");
    }

Upvotes: 1

oobe
oobe

Reputation: 458

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 :/

Upvotes: 0

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60744

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

Upvotes: 2

Related Questions