目標:洗掉嵌入在字串中的數字。
示例:let testString = "5What's9 wi3th this pro9ject I'm try905ing to build."
期望的輸出:testString = "5What's9 with this project I'm trying to build"
我試過的:
let resultString = testString
.replacingOccurrences(of: "\\b[:digit:]\\b", with: "", options: .regularExpression)
// fails, returns string as is
let resultString = testString
.replacingOccurrences(of: "(\\d )", with: "", options: .regularExpression)
// fails, returns all numbers removed from string.. close
let resultString = testString
.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
// removes all numbers from string.. close
我們如何才能洗掉僅在單詞內部的數字?
uj5u.com熱心網友回復:
我們可以嘗試對以下模式進行正則運算式替換:
(?<=\S)\d (?=\S)
這僅匹配兩側由非空白字符包圍的數字。更新代碼:
let resultString = testString
.replacingOccurrences(of: "(?<=\\S)\\d (?=\\S)", with: "", options: .regularExpression)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531140.html
