Johnny_D
Johnny_D

Reputation: 4652

Regular expression for csv with commas and no quotes

I'm trying to parse really complicated csv, which is generated wittout any quotes for columns with commas.
The only tip I get, that commas with whitespace before or after are included in field.

Jake,HomePC,Microsoft VS2010, Microsoft Office 2010

Should be parsed to

Jake
HomePC
Microsoft VS2010, Microsoft Office 2010

Can anybody advice please on how to include "\s," and ,"\s" to column body.

Upvotes: 0

Views: 1016

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

If your language supports lookbehind assertions, split on

(?<!\s),(?!\s)

In C#:

string[] splitArray = Regex.Split(subjectString, 
    @"(?<!\s) # Assert that the previous character isn't whitespace
    ,         # Match a comma
    (?!\s)    # Assert that the following character isn't whitespace", 
    RegexOptions.IgnorePatternWhitespace);

Upvotes: 2

Saurabh
Saurabh

Reputation: 1406

Try this. It gave me the desired result which you have mentioned.

StringBuilder testt = new StringBuilder("Jake,HomePC,Microsoft VS2010, Microsoft Office 2010,Microsoft VS2010, Microsoft Office 2010");
Pattern varPattern = Pattern.compile("[a-z0-9],[a-z0-9]", Pattern.CASE_INSENSITIVE);
Matcher varMatcher = varPattern.matcher(testt);
List<String> list = new ArrayList<String>();
int startIndex = 0, endIndex = 0;
boolean found = false;
while (varMatcher.find()) {
endIndex = varMatcher.start()+1;
if (startIndex == 0) {
list.add(testt.substring(startIndex, endIndex));
} else {
startIndex++;
list.add(testt.substring(startIndex, endIndex));
}
startIndex = endIndex;
found = true;
}
if (found) {
if (startIndex == 0) {
list.add(testt.substring(startIndex));
} else {
list.add(testt.substring(startIndex + 1));
}
}
for (String s : list) {
System.out.println(s);
}

Please note that the code is in Java.

Upvotes: 0

sarveshseri
sarveshseri

Reputation: 13985

split by r"(?!\s+),(?!\s+)"

in python you can do this like

import re
re.split(r"(?!\s+),(?!\s+)", s) # s is your string

Upvotes: 0

Related Questions