How can we split a string according to a specific range? Swift

Hassan Taleb

How can we split a string according to a specific range and put the sliced items in arrays like the example below:

let sentence = "Str1 {M} Str2 {/M} Str3 {M} Str4 {/M} {M} Str5 {/M} Str6 {M} Str7 {/M}"

Note: Str1 , Str2 ... are a strings

What I want: (1,2,3 and 4)

 1) OutputBetweenM = [Str2, Str4, Str5, Str7]
 2) OutputOutsideM = [Str1, Str3, Str6]
 3) OutputBetweenM_Edited = [Str2Edited, Str4Edited, Str5Edited, Str7Edited]
 4) Output3 = [Str1, Str2Edited, Str3, Str4Edited, Str5Edited, Str6, Str7Edited]

and finally rewrite the new sentence by adding the new items in Output3 together (easy to me) to get this:

let Final_sentence = "Str1 {M} Str2Edited {/M} Str3 {M} Str4Edited {/M} {M} Str5Edited {/M} Str6 {M} Str7Edited {/M}"

That is what I try to do:
1st code:

let from = NSRegularExpression.escapedPattern(for: "{M}") // escapedPattern
let to = NSRegularExpression.escapedPattern(for: "{/M}")
let regex = "(?<=\(from))(.*?)(?=\(to))"
let ranges = sentence.ranges(of: regex, options: .regularExpression)
let matches = ranges.map{ sentence[$0] }
print(matches) /* OutputBetweenM: [" Str2 ", " Str4 ", " Str5 ", " Str7 "]  ( Correct ) */

2nd Code:

let from = NSRegularExpression.escapedPattern(for: "{M}") // escapedPattern
let to = NSRegularExpression.escapedPattern(for: "{/M}")

let regexIncluding = from + ".*?" + to
let rangesIncluding = sentence.ranges(of: regexIncluding, options: .regularExpression)
var mutableSentence = sentence
print(mutableSentence)
for range in rangesIncluding.reversed() {
    mutableSentence.replaceSubrange(range, with: "\n")
}
let excludedOnes = mutableSentence.components(separatedBy: .newlines)
print(excludedOnes) /* OutputOutsideM: ["Str1 ", " Str3 ", " ", " Str6 ", ""]  ( InCorrect :/) 
 Correct one : ["Str1 ", " Str3 ", " Str6 "] */

Extension used: from a post in this page : Index of a substring in a string with Swift

func ranges(of string: String, options: CompareOptions = .literal) -> [Range<Index>] {
    var result: [Range<Index>] = []
    var start = startIndex
    while let range = range(of: string, options: options, range: start..<endIndex) {
        result.append(range)
        start = range.lowerBound < range.upperBound ? range.upperBound : index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
    }
    return result
}

And after that , I don't know how I can put them like Output3 , thx to @leo-dabus for his help.
Thanks in advance!

Leo Dabus

The question it is not so clear but if I understood correctly that should be simple. You just need to zip together the excludedOnes and the edited ones, enumerate the zipped array and append each element of the tuple to the Output3. Once you have the Output3 array just filter where trimmingCharacters(in: .whitespaces) is not equal to an empty string and replace the ranges found with your edited array:

let excludedOnes = ["Str1 ", " Str3 ", " ", " Str6 ", ""]
let OutputBetweenM_Edited = ["Str2Edited", "Str4Edited", "Str5Edited", "Str7Edited"]

let zipped = zip(excludedOnes,OutputBetweenM_Edited)
print(zipped)
var output3: [String] = []
for item in zipped {
    output3.append(item.0)
    output3.append(item.1)
}
output3 = output3.filter{ $0.trimmingCharacters(in: .whitespaces) != "" }   
print("output3:",output3)

output3: ["Str1 ", "Str2Edited", " Str3 ", "Str4Edited", "Str5Edited", " Str6 ", "Str7Edited"]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How can I split a column in a specific range?

From Dev

How can we split a complex string

From Dev

Split a Column in multiple columns according to a specific string

From Dev

How can I match specific character between specific range in the string?

From Dev

How to split a string in Swift

From Dev

How can I validate if a string contain specific chars range

From Dev

Split a Column in multiple columns according to a specific string according to irregular number of items between each string

From Dev

How to convert a string to an array according to a specific separator?

From Dev

How can show ages according specific years?

From Dev

How to split string by specific keywords?

From Dev

How to split string to a specific pattern?

From Dev

How to split a specific string in Java

From Dev

How to split string by specific keywords?

From Dev

How can we split a projector projection?

From Dev

How can we split a string using starts with regular expression (/^myString/g)

From Dev

Bash split string according to string

From Dev

How can i replace a specific word in a string in swift?

From Dev

How can i replace a specific word in a string in swift?

From Dev

Python 3 : How to split a string for a range of characters?

From Dev

How can I split string to lines with specific width using unix commands? When the input string is infinite?

From Dev

How fast can we make a specific tr?

From Dev

How we can calculate starting and ending indices of specific string in a cell array in MATLAB?

From Dev

How can i split html data according to params

From Dev

how to check if time is within a specific range in swift

From Dev

Split table according to string in a column

From Dev

Split string according to commas in R

From Dev

split a string according to pattern in R

From Dev

How we can change variable of protocol in Swift

From Dev

Ruby - How to split a string before specific keywords

Related Related

  1. 1

    How can I split a column in a specific range?

  2. 2

    How can we split a complex string

  3. 3

    Split a Column in multiple columns according to a specific string

  4. 4

    How can I match specific character between specific range in the string?

  5. 5

    How to split a string in Swift

  6. 6

    How can I validate if a string contain specific chars range

  7. 7

    Split a Column in multiple columns according to a specific string according to irregular number of items between each string

  8. 8

    How to convert a string to an array according to a specific separator?

  9. 9

    How can show ages according specific years?

  10. 10

    How to split string by specific keywords?

  11. 11

    How to split string to a specific pattern?

  12. 12

    How to split a specific string in Java

  13. 13

    How to split string by specific keywords?

  14. 14

    How can we split a projector projection?

  15. 15

    How can we split a string using starts with regular expression (/^myString/g)

  16. 16

    Bash split string according to string

  17. 17

    How can i replace a specific word in a string in swift?

  18. 18

    How can i replace a specific word in a string in swift?

  19. 19

    Python 3 : How to split a string for a range of characters?

  20. 20

    How can I split string to lines with specific width using unix commands? When the input string is infinite?

  21. 21

    How fast can we make a specific tr?

  22. 22

    How we can calculate starting and ending indices of specific string in a cell array in MATLAB?

  23. 23

    How can i split html data according to params

  24. 24

    how to check if time is within a specific range in swift

  25. 25

    Split table according to string in a column

  26. 26

    Split string according to commas in R

  27. 27

    split a string according to pattern in R

  28. 28

    How we can change variable of protocol in Swift

  29. 29

    Ruby - How to split a string before specific keywords

HotTag

Archive