Last active
September 13, 2017 16:25
-
-
Save lkatney/d304403badbd9ccaf2dead4bdc20b62e to your computer and use it in GitHub Desktop.
Handle Commas In CSV Columns - Apex(http://blog.lkatney.com/2017/09/13/handle-commas-in-csv-columns-apex/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String csvLine = 'Test,Check,[email protected], "19, Link road, A1SH10, India", companyName, "companyStreet, CompanyCity, CompanyCountry"'; | |
String prevLine = csvLine; | |
Integer startIndex; | |
Integer endIndex; | |
while(csvLine.indexOf('"') > -1){ | |
if(startIndex == null){ | |
startIndex = csvLine.indexOf('"'); | |
csvLine = csvLine.substring(0, startIndex) + ':quotes:' + csvLine.substring(startIndex+1, csvLine.length()); | |
}else{ | |
if(endIndex == null){ | |
endIndex = csvLine.indexOf('"'); | |
csvLine = csvLine.substring(0, endIndex) + ':quotes:' + csvLine.substring(endIndex+1, csvLine.length()); | |
} | |
} | |
if(startIndex != null && endIndex != null){ | |
String sub = csvLine.substring(startIndex, endIndex); | |
sub = sub.replaceAll(',', ':comma:'); | |
csvLine = csvLine.substring(0, startIndex) + sub + csvLine.substring(endIndex, csvLine.length()); | |
startIndex = null; | |
endIndex = null; | |
} | |
} | |
System.debug('prevLine:::'+prevLine); | |
System.debug('csvLine:::'+csvLine); | |
for(String column : csvLine.split(',')){ | |
column = column.replaceAll(':quotes:', '').replaceAll(':comma:', ','); | |
System.debug('column::'+column); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment