user1662450
user1662450

Reputation: 17

How to create C# Regex to Split the string with some words in quotations?

I have a string as in the following format:

"one,",2,3,"four " ","five"

I need output in the following format:

one,
2
3
four " 
five

Can anyone help me to create Regex for the above?

Upvotes: 0

Views: 218

Answers (2)

Martin
Martin

Reputation: 2300

You can do this without Regex. It's not clear to me, what you're trying to do though. I've adjusted the code for the updated question:

var text = "\"one\",2,3,\"four \"\",\"five\"";

var collection = text
    .Split(',')
    .Select(s =>
                {
                    if (s.StartsWith("\"") && s.EndsWith("\""))
                    {
                        s = s.Substring(1, s.Length - 2);
                    }
                    return s;
                })
    .ToList();

foreach (var item in collection)
{
    Console.WriteLine(item);
}

I've added another sample for you, which uses a CSV reader. I've installed the "CsvHelper" package from NuGet:

const string text = "\"one,\",2,3,\"four \"\"\",\"five\"";

using (var textReader = new StringReader(text))
using (var reader = new CsvReader(textReader))
{
    reader.Configuration.Delimiter = ',';
    reader.Configuration.AllowComments = false;
    reader.Configuration.HasHeaderRecord = false;

    if (reader.Read())
    {
        foreach (var item in reader.CurrentRecord)
        {
            Console.WriteLine(item);
        }
    }
}

Upvotes: 1

ParPar
ParPar

Reputation: 7569

  string newString = Regex.Replace(oldString, @'[^",]', ' ');

I hope the regular expression is good, but I just want you you to see the idea.

EDIT:

 string newString = Regex.Replace(oldString, @'[^",]', '\n');

Upvotes: 0

Related Questions