Tom
Tom

Reputation: 1057

Regex to select all commas up to a specific character

I am having a terrible time with regular expressions. Its terrible for me to admit, but I just don't use them enough to be really good when I need to be. Basically due to the way our application runs, I have the contents of a .csv file pulled out into a string. I need to essentially insert a new row above and below what already exists. The amount of columns can change depending on the report. What I would like to do is grab all commas without any other characters (including whitespace) up to the first set of \r\n in the string. This way I have all the columns and I can insert a blank row up top and populate the columns with what I need. Here is an example of the .csv text:

"Date, Account Code, Description, Amount\r\n23-Apr-13,12345,Account1,$12345\r\n"

What I would like the regex to grab:

",,," or ",,,\r\n"

I just cannot seem to get this. Thank you.

Upvotes: 0

Views: 272

Answers (3)

Jesse
Jesse

Reputation: 8749

You actually don't need to complicate your code with Regular Epressions to accomplish what you want: to count the columns.

Here's an extremely simple method:

String textline = csvtext.Substring(0, csvtext.IndexOfAny(Environment.NewLine.ToCharArray()));
int columns = textline.Split(',').Length;

Now the columns variable has your total number of columns.


The first line grabs just the first line out of the CSV text. The second line splits that text into an array separated by commas (,), and returns the total number.

Upvotes: 2

Nandha Kumar
Nandha Kumar

Reputation: 126

you can make use the below regex (?<=[\d\w\s])(\r|\n|,)(?=[\d\w\s\W]) to match , and new line characters, Use can make use of Regex.Replace("inputstring","regexpattern","replacechar", RegexOptions.IgnoreCase)

This can be done by string operations itself

string[] strs= inputstr.split(new string[]{"\n","\r",","}, StringSplitOptions.RemoveEmptyEntries);
foreach(string str in strs)
{
// do you part
}

Upvotes: 0

Alex
Alex

Reputation: 7919

You don't need a regex for this.

string firstLine = file.ReadLines().First();
int numCommas = firstLine.Count(c => c == ',');
string commaString = new String(',', numCommas);

If you don't have access to file.ReadLines() method, you can use the following from this link:

string firstline = test.Substring(0, test.IndexOf(Environment.NewLine));

Upvotes: 2

Related Questions