ios - Split string return multiple values with Regex in swift 4


Keywords:ios 


Question: 

I want to create an extension function which will split a string to an array with a format. Example:

  • Source string:

    "1~1895|usd||A:123000|B:1234"
    
  • Pattern should like this:

    "int~int|string||A:int|B:int|C:int"
    
  • Should return

    [1, 1895, "usd", 123000, 1234, nil]
    

I am trying to split with regex but I don't know how to return multiple values.


1 Answer: 

Actually this would be a good use case for a Scanner. Scan the first number, scan through the twiddle, scan the next number, scan through the pipe, scan the string up to the pipe, scan through the two pipes, scan through to the colon, scan the number, and so forth.