簡體   English   中英

使用條件快速替換出現的字符串

[英]Swift replace occurrence of string with condition

我有下面的字符串

<p><strong>I am a strongPerson</strong></p>

我想像這樣隱蔽這個字符串

<p><strong>I am a weakPerson</strong></p>

當我嘗試下面的代碼

let old = "<p><strong>I am a strongPerson</strong></p>"
let new = old.replacingOccurrences(of: "strong", with: "weak")
print("\(new)")

我正在輸出像

<p><weak>I am a weakPerson</weak></p>

但是我需要這樣的輸出

<p><strong>I am a weakPerson</strong></p>

我的條件是

1.僅當word不包含這些HTML標記(例如“ <>”)時才必須替換。

幫幫我。 提前致謝。

您可以使用正則表達式來避免單詞出現在標簽中:

let old = "strong <p><strong>I am a strong person</strong></p> strong"
let new = old.replacingOccurrences(of: "strong(?!>)", with: "weak", options: .regularExpression, range: nil)
print(new)

我添加了“強”一詞的一些額外用法來測試極端情況。

訣竅是使用(?!>) ,這基本上意味着忽略任何結尾有>匹配項。 查看NSRegularExpression的文檔,並找到“負超前斷言”的文檔。

輸出:

弱<p> <strong>我是一個弱者</ strong> </ p>

請嘗試以下操作:

let myString = "<p><strong>I am a strongPerson</strong></p>"
if let regex = try? NSRegularExpression(pattern: "strong(?!>)") {

 let modString = regex.stringByReplacingMatches(in: myString, options: [], range: NSRange(location: 0, length:  myString.count), withTemplate: "weak")
  print(modString)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM