-1

i have a semicolon separates string, that contains values of every type. string and date values are in quotations.

Now i have an evil string, where an inner string contains s semicolon, that i need to remove (replace by nothing).

eg:

"Value1";0;"Value2";4711;"Evil; Value";"2015-09-03"

in C#:

string value = "\"Value1\";0;\"Value2\";4711;\"Evil; Value\";\"2015-09-03\""

So how to replace all semicolons, that are in quotations? can anybody help?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Dosihris
  • 85
  • 1
  • 8
  • Hey guys, i cant read an answer there. Please read my post carefully! I DO NOT!! Have a file, i just have a string! So tell me how to do this with the TextFieldParser??? – Dosihris Sep 04 '15 at 07:45
  • Thats the correct answer! Open this thread again to post it to anybody else! StringBuilder builder = new StringBuilder(textBox1.Text); foreach (Match m in Regex.Matches(builder.ToString(), "\".*?\"")) { if (m.Value.Contains(";")) // If it contains a semicolon { string temp = m.Value.Replace(";", ""); builder.Replace(m.Value, temp); } } var parts = builder.ToString().Split(new char[] { ';' }); – Dosihris Sep 04 '15 at 08:17

2 Answers2

1

Regex is awful at handling delimited strings. It can do it, but it's not often as good of a choice as it first appears. This is one of several reasons why.

Instead, you should use a dedicated delimited string parser. There are (at least) three built into the .Net framework. The TextFieldParser type is one of those, and it will handle this correctly.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Interesting. Was wondering how I had never seen this class before. I guess it's part of Microsoft.VisualBasic.dll. Hmm...curious. – aquinas Sep 03 '15 at 19:45
  • It's part of that namespace for compatibility reasons, but it works great from C#. – Joel Coehoorn Sep 03 '15 at 20:27
  • It can only handle files, no simple strings! – Dosihris Sep 04 '15 at 07:46
  • Hey guys, you are marking it as duplicate all the time, but you are not answering my question. Show me, how to use the TextFieldPArser with a string! If you can not show me, how can it be a duplucate? – Dosihris Sep 04 '15 at 08:40
  • Older now, but this handles _streams_, not files. You can easily get a stream from a string via the StringReader class. – Joel Coehoorn Sep 18 '15 at 17:46
-1

You should try this i.e to match only those semicolons which is not preceded by : :

(?<=[^"]);

Here is demo

Arunesh Singh
  • 3,489
  • 18
  • 26