2012-07-13 74 views
0

我想解析真正複雜的csv,它是用逗號生成的任何引號。
我得到的唯一提示是,前面或後面帶有空白的逗號都包含在字段中。csv用逗號和不帶引號的正則表達式

Jake,HomePC,Microsoft VS2010, Microsoft Office 2010 

應該解釋爲

Jake 
HomePC 
Microsoft VS2010, Microsoft Office 2010 

任何人可以建議,請於如何將 「\ S」 和 「\ S」 到柱體。由R

+1

拆分上',(\ S?!)(<\ s?!)'也許? – Wrikken 2012-07-13 11:32:33

+0

@Wrikken,不太擅長正則表達式,可以請你使用樣本。謝謝。 – 2012-07-13 11:35:52

+1

如果不正確地轉義數據,這顯然不是CSV文件。如果可能的話,我會得到數據的原始信息以創建[正確格式化的CSV文件](http://en.wikipedia.org/wiki/Comma-separated_values) – Brad 2012-07-13 11:36:24

回答

2

如果你的語言支持後向斷言,各執

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

在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); 
+0

我正在使用C#,它爲它工作嗎? – 2012-07-13 14:10:16

+0

是的,只要記住將正則表達式放在一個逐字字符串('@「...」'')中即可。 – 2012-07-13 14:35:16

0

分裂 「(?!\ S +),(?!\ S +)」

在Python中,你可以做到這一點像

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

這是不正確和不雅的。你需要一個lookbehind斷言,你不需要量詞。 – 2012-07-13 13:12:23

0

試試這個。它給了我你所提到的理想結果。

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

請注意,代碼是用Java編寫的。