import Foundation
let pattern = #"(^reflectance_\d_)(\S*)$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
reflectance_7_myd21a1_emissivity_29
reflectance_7_myd21a1_emissivity_29_savitzkygolay
reflectance_7_myd21a1_emissivity_31
reflectance_7_myd21a1_emissivity_31_savitzkygolay
reflectance_3_myd21a1_emissivity_32
reflectance_2_myd21a1_emissivity_32_savitzkygolay
reflectance_1_mcd43a3_albedo_bsa_band1
reflectance_3_mcd43a3_albedo_bsa_band2
reflectance_7_mcd43a3_albedo_bsa_nir
reflectance_7_mcd43a3_albedo_bsa_shortwave
reflectance_7_mcd43a3_albedo_bsa_vis
reflectance_7_mcd43a3_albedo_wsa_band1
reflectance_7_mcd43a3_albedo_wsa_band2
reflectance_7_mcd43a3_albedo_wsa_nir
reflectance_7_mcd43a3_albedo_wsa_shortwave
reflectance_7_mcd43a3_albedo_wsa_vis
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"($1)vs_$2"#
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