-3

I have a [String] that goes like

ABC,JKL,123,12,PQR

ABC,"XY, Z",654,54,PQR

The resulting array should look like this:

["ABC","JKL","123","12",PQR],["ABC","XY, Z","654","54","PQR"]

This is what I have tried already, but this does not work as I want in second element's case:

content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") }
2
  • 2
    That's great. What have you tried so far to accomplish this? Commented Sep 27, 2019 at 7:46
  • as of now I am using -> content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") } , but this does not work as I want in second element's case Commented Sep 27, 2019 at 7:56

1 Answer 1

0

Idea behind solution:

You want to split your string into an array on every occurrence of ,, accounting for data contained within " as a single item.

To do this you have to use the global split function with a regex pattern.

Code sample:

extension String
{
  func splitCommas() -> [Stirng] {
    let pattern = ",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)" //regex pattern for commas that are not within quotes
    if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
      let string = self as NSString
      return regex.matches(in:inputString, range: NSMakeRange(0, inputString.utf16.count)).map {
        string.substring(with: $0.range).replacingOccurrences(of: ",", with: "") //removing all instances of commas
      }
    }
    return []
  }
}

Hope this helps! ;)

Updates

Updated code to more modern example.

Also implemented function as a String extension for usability within all of the String variables.

Sign up to request clarification or add additional context in comments.

4 Comments

What version of swift is this?
Tamil Nadu,Tenkasi ,"MANMATHAN,M.",M,60,SC,IND,3331,0,1382081 -> [",Tenkasi ", ",\"MANMATHAN,M.\"", ",M", ",60", ",SC", ",IND", ",3331", ",0", ",1382081"]. Nope
@KishanSadhwani, can't you post proper test data in your question so we understand what kind of strings we are dealing with?
@KishanSadhwani If I understood it correctly, it seems like the first string (Tamil Nadu) is missing and the output array still has the commas in them?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.