import Foundation
let pattern = #"^[\*].+?SemprePresente1=(\d{2}\/\d{4}).+?SemprePresente2=(\d{6})(?:(?!Opcional=)[^\*])+(Opcional=(\d+,\d+))?[^\*]+"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .dotMatchesLineSeparators])
let testString = #"""
********************
SemprePresente1=09/2019
SemprePresente2=987456
Um monte de coisas
Que não preciso
Opcional=698,00
Mais coisas que não preciso
********************
SemprePresente1=06/2019
SemprePresente2=123658
Um monte de coisas
Que não preciso
********************
SemprePresente1=09/2019
SemprePresente2=987699
Um monte de coisas
Opcional=9999,00
Mais coisas que não preciso
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\1;\2;\4\n"#
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