3

I'm trying to replace the occurrences of all spaces and special characters within a string in Swift.

I don't know what the RegEx would be in Swift.

I am trying to use the built in function .replacingOccurences(of:) and passing in my RegEx as the string-protocol, while the code compiles, no changes are made.

Online there are many resources on how to replace occurrences in Swift however, the solutions are far more complicated than what seems to be nessacary.

How can I properly return this output (Current Strategy):

let word = "Hello World!!"
func regEx(word: String) -> String {
   return word.replacingOccurrences(of: "/[^\\w]/g", with: "")
}
// return --> "HelloWorld"
3
  • Use "\\W+".... Commented Jul 16, 2018 at 20:02
  • Is there a website like regexr.com for swift? Commented Jul 16, 2018 at 20:04
  • Swift uses ICU regex library, I do not know any online regex tester that supports it, but PCRE is close though there is a considerable difference. Commented Jul 16, 2018 at 20:06

2 Answers 2

5

You may use

return word.replacingOccurrences(of: "\\W+", with: "", options: .regularExpression)

Note the options: .regularExpression argument that actually enables regex-based search in the .replacingOccurrences method.

Your pattern is [^\w]. It is a negated character class that matches any char but a word char. So, it is equal to \W.

The /.../ are regex delimiters. In Swift regex, they are parsed as literal forward slashes, and thus your pattern did not work.

The g is a "global" modifier that let's a regex engine match multiple occurrences, but it only works where it is supported (e.g. in JavaScript). Since regex delimiters are not supported in Swift regex, the regex engine knows how to behave through the .replacingOccurrences method definition:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

If you need to check ICU regex syntax, consider referring to ICU User Guide > Regular Expressions, it is the regex library used in Swift/Objective-C.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to set the options to .regularExpression
Yeah, I was testing it now, and was going to update.
0

Additionally, you could extend String and accomplish the same bit. But if it's homework and they said function stick with that.

var word = "Hello World!!!"

extension String {
    func regEx() -> String {
        return self.replacingOccurrences(of: "\\W+", with: "", options: .regularExpression, range: nil)
    }
}

word.regEx()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.