在 Swift 中使用正则表达式 [英] Using regex in Swift

查看:68
本文介绍了在 Swift 中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换 Swift 字符串中所有空格和特殊字符的出现.

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

我不知道 Swift 中的 RegEx 是什么.

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

我正在尝试使用内置函数 .replacingOccurences(of:) 并将我的 RegEx 作为字符串协议传递,而代码编译时,没有进行任何更改.

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.

网上有很多关于如何在 Swift 中替换出现的资源,然而,解决方案远比看似必要的复杂.

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"

推荐答案

您可以使用

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

注意 options: .regularExpression 参数,它实际上在 .replacingOccurrences 方法中启用了基于正则表达式的搜索.

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

你的模式是[^\w].它是一个否定字符类,匹配除字符字符以外的任何字符.因此,它等于 \W.

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

/.../ 是正则表达式分隔符.在 Swift 正则表达式中,它们被解析为文字正斜杠,因此您的模式不起作用.

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

g 是一个全局"修饰符,它让正则表达式引擎匹配多次出现,但它只在支持它的地方工作(例如在 JavaScript 中).由于 Swift 正则表达式不支持正则表达式分隔符,正则表达式引擎知道如何通过 .replacingOccurrences 方法 定义:

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.

如果您需要检查 ICU 正则表达式语法,请考虑参考 ICU 用户指南 > Regular Expressions,它是 Swift/Objective-C 中使用的正则表达式库.

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.

这篇关于在 Swift 中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆