-7
A
回答
3
一個簡單的正則表達式:
let sentence = "This is \"table\". There is an \"apple\" on the \"table\""
let pattern = "\"[^\"]+\"" //everything between " and "
let replacement = "____"
let newSentence = sentence.replacingOccurrences(
of: pattern,
with: replacement,
options: .regularExpression
)
print(newSentence) // This is ____. There is an ____ on the ____
如果你想保持相同的字符數,那麼你可以在比賽迭代:
let sentence = "This is table. There is \"an\" apple on \"the\" table."
let regularExpression = try! NSRegularExpression(pattern: "\"[^\"]+\"", options: [])
let matches = regularExpression.matches(
in: sentence,
options: [],
range: NSMakeRange(0, sentence.characters.count)
)
var newSentence = sentence
for match in matches {
let replacement = Array(repeating: "_", count: match.range.length - 2).joined()
newSentence = (newSentence as NSString).replacingCharacters(in: match.range, with: "\"" + replacement + "\"")
}
print(newSentence) // This is table. There is "__" apple on "___" table.
相關問題
- 1. PHP快速替換字符之間字符串的內容
- 2. 替換字符串之間的字符
- 3. 快速多字符串替換
- 4. 替換兩個字符串之間的字符串iphone sdk
- 5. 在Java中的2個字符串之間替換字符串
- 6. 替換兩個字符串之間的字符串
- 7. 用JavaScript替換4個字符之間的字符串中的字符串
- 8. ActionScript之間替換字符串?
- 9. sed - 用另一個字符串替換兩個字符串之間的字符
- 10. python用字符串之間的特殊字符替換空格
- 11. 提取和替換字符之間的字符串
- 12. 正則表達式替換字符串之間的字符
- 13. 特定字符串之間的替換字符
- 14. 替換/刪除兩個字符之間的字符串
- 15. 如何替換Sublime中兩個字符之間的字符串
- 16. 用通配符替換快速字符串
- 17. PHP快速輕鬆地替換字符?
- 18. 替換字符串字符
- 19. 用子串替換後續分隔符之間的字符串
- 20. 如何兩個字符串之間替換字符
- 21. 替換部分字符串在特殊字符之間
- 22. 替換字符串中特定字符之間的特定字符
- 23. 替換字符串內的字符串
- 24. 字符串中的字符串替換
- 25. 快速從UInt8轉換爲字符串
- 26. 快速字符串爲byte []轉換
- 27. 快速字符串替換mod_rewrite的問題
- 28. 替換字符串之前的字符串?
- 29. 從字符串快速startIndex
- 30. AnyObject以快速字符串