[英]Replace matches using regex by modifying matched string in swift
我試圖在 swift 中使用正則表達式替換匹配的字符串,我的要求如下
originalString = "It is live now at Germany(DE)"
我希望(" ")
的字符串即DE
用空格分隔,即“DE”
所以被替換的字符串應該是"It is live now at Germany(DE)"
我試過下面的代碼
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)
輸出是It is live now at Germany (DE)
,我知道這不是必需的。 這里它基於模板,我們不能根據匹配的字符串值進行修改。 有沒有辦法實現這一目標?
提前致謝
您可以使用
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)
要不就
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) )
輸出: It is live now at Germany(DE) or (SOFE)
圖案詳情
(?<=\\\\G(?<!\\\\A)|\\\\()
- 一個積極的后視,匹配一個位置緊跟在(
或在前面的成功匹配的末尾[A-Za-z]
- 匹配並使用任何 ASCII 字母(?=[A-Za-z]+\\\\))
- 一個正向前瞻,匹配緊跟其后是 1+ ASCII 字母和)
字符的位置。 替換中的$0
將整個匹配值插入到結果字符串中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.