使用匹配的正则表达式代码替换单词
Replace words using the matching regex code
我需要使用 Swift 正则表达式替换给定字符串中的单词。
Ignore numbers (ex: 2000 or 2,000)
But if a number contains characters, replace it (ex: H3llo)
let givenString = "I will keep this 3,000 short. It is a quite common task to 20ff to split a string by 500gg. If you’re a native 500 speaker?"
let range = NSRange(location: 0, length: givenString.count)
var pattern = "[a-zA-Z/\-']{2,}" // I need the correct pattern, this one if failing.
let regex = try! NSRegularExpression(pattern: pattern, options: [])
print(regex.stringByReplacingMatches(in: givenString, options: [], range: range, withTemplate: "hello"))
结果:
I hello hello hello 3,000 hello. It is a hello hello hello to 20ff to hello a hello by 500gg. If you’re a hello 500 hello?
20ff 和 500gg 应该被替换为 ''hello'
预期结果:
I hello hello hello 3,000 hello. It is a hello hello hello to hello to hello a hello by hello. If you’re a hello 500 hello?
也许你可以试试:
\d?\S\S+[a-zA-Z]
我需要使用 Swift 正则表达式替换给定字符串中的单词。
Ignore numbers (ex: 2000 or 2,000)
But if a number contains characters, replace it (ex: H3llo)
let givenString = "I will keep this 3,000 short. It is a quite common task to 20ff to split a string by 500gg. If you’re a native 500 speaker?"
let range = NSRange(location: 0, length: givenString.count)
var pattern = "[a-zA-Z/\-']{2,}" // I need the correct pattern, this one if failing.
let regex = try! NSRegularExpression(pattern: pattern, options: [])
print(regex.stringByReplacingMatches(in: givenString, options: [], range: range, withTemplate: "hello"))
结果:
I hello hello hello 3,000 hello. It is a hello hello hello to 20ff to hello a hello by 500gg. If you’re a hello 500 hello?
20ff 和 500gg 应该被替换为 ''hello'
预期结果:
I hello hello hello 3,000 hello. It is a hello hello hello to hello to hello a hello by hello. If you’re a hello 500 hello?
也许你可以试试:
\d?\S\S+[a-zA-Z]