import Foundation
let pattern = #"(?<=(?:\[embed\])|(?:\[embed\]\s)|(?:))(https?:\/\/)(:?www\.)?(:?youtube\.com\/watch|youtu\.be\/)([\w\?=\&]+)(?=(?:\[\/embed\])|(?:\s\[\/embed\])|(?:))"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .dotMatchesLineSeparators])
let testString = #"""
bla https://www.youtube.com/watch?v=Vpg9yizPP_g
http://www.youtube.com/watch?v=Vpg9yizPP_g bla
[embed]https://www.youtube.com/watch?v=Vpg9yizPP_g[/embed] bla
[embed] https://www.youtube.com/watch?v=Vpg9yizPP_g [/embed]
[embed]http://www.youtube.com/watch?v=Vpg9yizPP_g[/embed]
[embed] http://www.youtube.com/watch?v=Vpg9yizPP_g [/embed]
bla https://youtube.com/watch?v=Vpg9yizPP_g bla
http://youtube.com/watch?v=Vpg9yizPP_g
[embed]https://youtube.com/watch?v=Vpg9yizPP_g[/embed]bla
bla[embed] https://youtube.com/watch?v=Vpg9yizPP_g [/embed]
[embed]http://youtube.com/watch?v=Vpg9yizPP_g[/embed]
[embed] http://youtube.com/watch?v=Vpg9yizPP_g [/embed]
https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
[embed]https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
[embed]http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
bla[embed] http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]bla
https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g bla
bla http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
[embed]https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
[embed]http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
https://youtu.be/Vpg9yizPP_g
http://youtu.be/Vpg9yizPP_g bla
[embed]https://youtu.be/Vpg9yizPP_g[/embed]
[embed] https://youtu.be/Vpg9yizPP_g [/embed]
[embed]http://youtu.be/Vpg9yizPP_g[/embed]
[embed] http://youtu.be/Vpg9yizPP_g [/embed]
<a href src="http://youtu.be/Vpg9yizPP_g">vid</a>
<a href src="http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g">vid</a>
<a href src="https://youtube.com/watch?v=Vpg9yizPP_g">vid</a>
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\1\2\3\4"#
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