import Foundation
let pattern = ##"""
(?<firstcapture> ~Start [^~]* ) #_(3)
(?<randomStuff> .*? ) #_(4)
(?<loop_first> #_(5 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (1)
) #_(5 end)
(?:
(?<loop_middle> #_(6 start)
(?:
(?:
~
(?: LOOP )
\d [^~]
)
.*?
)*
) #_(6 end)
(?<loop_last> #_(7 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (2)
) #_(7 end)
)?
(?<end> ~End [ ] stuff~ ) #_(8)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = #"""
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~End stuff~
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"${firstcapture}${randomStuff}${loop_last}${loop_middle}${loop_first}${end}"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression