0

I need to get array of string from a string e.g from this string

"1. Grease cake pans with oil spray and preheat your oven to 350°F.2. Dissolve the coffee powder in the hot water.3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."

to

["1. Grease cake pans with oil spray and preheat your oven to 350°F.",
 "2. Dissolve the coffee powder in the hot water."
 "3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."]

on the bases of digits in the strings, in normal cases

String.components(separatedBy: <#T##CharacterSet#>)

works fine but in this case I can't figure it out. thanks in advance

1
  • 1
    Whatever solution you use, make sure to think about ambiguous strings like: "1. Preheat oven to gas mark 2. (300ºF in the US.)2. Place item in oven from step 1.3. Mix other items." Working out the precise rules your string will follow (if there are any such rules), is an important part of making this robust. For example, does there have to be a period before the number? (But if so, think about changing the above string to "gas mark 0.5. (200º in the US).) Do you have any control over the input strings? Commented Jan 29, 2021 at 15:41

1 Answer 1

1

You can try matching any digit (1 or more) followed by a dot and a space. Then anything other than a period followed by a single period:

let string = "1. Grease cake pans with oil spray and preheat your oven to 350°F.2. Dissolve the coffee powder in the hot water.3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."

let pattern = #"\d{1,}. {1}[^.]+.{1}"#

let sentences = try! NSRegularExpression(pattern: pattern)
    .matches(in: string, range: .init(string.startIndex..., in: string))
    .map {  string[Range($0.range, in: string)!] }

print(sentences)  // "["1. Grease cake pans with oil spray and preheat your oven to 350°F.", "2. Dissolve the coffee powder in the hot water.", "3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."]\n"
Sign up to request clarification or add additional context in comments.

Comments

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.