swift中没有直接的方法来实现和执行正则表达式。
我想在字符串中搜索数字并将其替换为另一个字符串。例如:
var numberString = "I have 567 horses in my barn"
var replacementString = "many"
如何搜索现有数字的索引并将其与我的字符串一起重新显示,使其看起来像:
var finalString = "i have many horses in my barn"
编辑:代码应考虑到数字的其他格式。所以即使是字符串也喜欢 var numberString =“我的谷仓里有5,675.00匹马”可以编辑
答案 0 :(得分:4)
在swift中有 no 直接的方法来实现和执行正则表达式。
let numberString = "I have 567 horses in my barn"
let replacementString = "many"
let finalString = numberString.replacingOccurrences(of: "\\d+", with: replacementString, options: .regularExpression)
答案 1 :(得分:1)
您可以使用正则表达式:
var numberString = "I have 567 horses in my barn"
var replacementString = "many"
if let range = numberString.range(of: "([0-9])+", options: .regularExpression, range: nil, locale: nil) {
numberString.replaceSubrange(range, with: replacementString)
}
//Result: "I have many horses in my barn"
答案 2 :(得分:1)
var str = "I have 567 horses in my barn"
let decimalCharacters = CharacterSet.decimalDigits
let decimalRange = str.rangeOfCharacter(from: decimalCharacters)
if decimalRange != nil {
print("Numbers found.. Replace this with the replacement string")
}
从上面的用法中,您可以获得字符串中数字的范围。然后你可以用替换字符串替换该字符串。