Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace matches using regex by modifying matched string in swift

Im trying to replace matched strings using regex in swift, my requirement is as below

originalString = "It is live now at Germany(DE)"

i want the string within the (" ") i.eDE to be separated by space i.e. "D E"

so replacedString should be "It is live now at Germany(D E)"

i tried below code

var value: NSMutableString = "It is live now at Germany(DE)"
let pattern = "(\\([A-Za-z ]+\\))"
let regex = try? NSRegularExpression(pattern: pattern)
regex?.replaceMatches(in: value, options: .reportProgress, range: 
NSRange(location: 0,length: value.length), withTemplate: " $1 ")
print(value)

output is It is live now at Germany (DE), i know it's not what is required. here it is based on the template where we cannot modify based on matched string value. Is there any way to achieve this ?

Thanks in advance

like image 354
Rajesh Rs Avatar asked Jun 17 '26 08:06

Rajesh Rs


1 Answers

You may use

var value: NSMutableString = "It is live now at Germany(DE) or (SOFE)"
let pattern = "(?<=\\G(?<!\\A)|\\()[A-Za-z](?=[A-Za-z]+\\))"
let regex = try? NSRegularExpression(pattern: pattern)
regex?.replaceMatches(in: value, options: .reportProgress, range: NSRange(location: 0,length: value.length), withTemplate: "$0 ")
print(value)

Or just

let val =  "It is live now at Germany(DE) or (SOFE)"
let pattern = "(?<=\\G(?<!\\A)|\\()[A-Za-z](?=[A-Za-z]+\\))"
print( val.replacingOccurrences(of: pattern, with: "$0 ", options: .regularExpression, range: nil) )

Output: It is live now at Germany(D E) or (S O F E)

Pattern details

  • (?<=\\G(?<!\\A)|\\() - a positive lookbehind that matches a location right after ( or at the end of the preceding successful match
  • [A-Za-z] - matches and consumes any ASCII letter
  • (?=[A-Za-z]+\\)) - a positive lookahead that matches a location that is immediately followed with 1+ ASCII letters and then a ) char.

The $0 in the replacement inserts the whole match value back into the resulting string.

like image 187
Wiktor Stribiżew Avatar answered Jun 19 '26 20:06

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!