swiftregexstringnsregularexpressionnscharacterset

Replace words using the matching regex code


I need to replace the words in a given string using Swift Regular Expression.

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"))

Result:

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 and 500gg should've been replaced by ''hello'

What's expected:

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?

Solution

  • Maybe you can try:

    \d?\S\S+[a-zA-Z]