Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex in Swift

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"
like image 518
Chris Avatar asked Apr 11 '26 20:04

Chris


1 Answers

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.

like image 198
Wiktor Stribiżew Avatar answered Apr 14 '26 14:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!