Using regex in Swift

前端 未结 2 2075
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 04:02

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 tr

2条回答
  •  迷失自我
    2021-01-07 04:53

    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.

提交回复
热议问题